Skip to content

Deep Q-networks, double targets and dueling heads

Fit Q(s, a) with a neural network from replayed experience and a lagging target network, see why the max in the target overestimates and how double targets curb it, and split the network into a state value and action advantages.

Advanced ~16 min11 steps

What runs in CodeSplash

You will be able to

  • Compute a DQN target, including at the end of an episode
  • Explain what the replay buffer and the target network each fix
  • Explain overestimation bias and how double Q targets reduce it
  • Describe the dueling head and why it subtracts the mean advantage
  • Run DQN in CodeSplash and compare the network's own estimate with the exact value

Read first

01

Q-learning with a network

Read

A deep Q-networkDeep Q-network (DQN)A neural network that estimates each action's value Q(s, a); the policy takes the action with the highest value. predicts Q(s,a)Q(s, a) for every action from the state. It trains toward the Bellman target:

y=r+γ (1−done) max⁡a′Qtarget(s′,a′),L=(Q(s,a)−y)2.y = r + \gamma\,(1 - \text{done})\, \max_{a'} Q_{\text{target}}(s', a'), \qquad L = \big(Q(s, a) - y\big)^2 .

At the end of an episode, done = 1 and the target is the reward alone. In the reference's example, three transitions get targets 2.98, 0 (a terminal step with zero reward) and 2.96, and a mean squared error of 1.905.

DExplorable · Gridworld: Q-learning, policy gradients and PPO

How do value-based and policy-gradient learners find a good route, and what makes them fail?

Learner

Q-learning learns action values; REINFORCE and PPO adjust a policy's preferences directly.

500

Trips from the start until the goal, the pit or 100 steps.

0.95

How much a reward one step later is worth now.

0.50

Step size of every update.

0.10

Q-learning only: share of steps that take a random action.

0.20

PPO only: how far the policy may move from the one that collected the batch.

0.10

Chance that a move turns 90° to either side.

Simulating…
Working…

Working…

02

Two stabilizers

Read

Training on each transition as it happens fails in two ways. Consecutive steps are nearly identical, so the network chases the last few. And the target moves every time the network does, so it chases itself.

The replay bufferExperience replayKeeping recent transitions and training on random minibatches of them, so updates aren't dominated by the last few steps. keeps recent transitions and trains on random minibatches of them. The target networkTarget network and double Q targetsTraining targets come from a lagged copy of the network; double targets pick the next action with one and value it with the other. is a lagging copy used only for yy, updated every so often. Both are on in CodeSplash's decide.rl_dqn.

03

The max is optimistic

Read

The max over noisy estimates picks the luckiest one. If every action is truly worth 1 but the estimates scatter around 1, their max is above 1, and targets built on it drift upward: overestimation biasOverestimation biasTaking the max over noisy action-value estimates picks the luckiest one, so Q-learning's targets drift upward..

Double Q targets choose the next action with the online network and score it with the target network:

y=r+γ Qtarget(s′,arg⁡max⁡a′Qonline(s′,a′)).y = r + \gamma\, Q_{\text{target}}\big(s', \arg\max_{a'} Q_{\text{online}}(s', a')\big).

In the reference's example, plain targets are 4.6 and 1.8; double targets for the same transitions are 1.9 and 0.45.

04

Dueling heads

Read

In many states the action barely matters. A dueling headDueling headSplits a Q-network's output into one state value plus action advantages centered on their mean. splits the output into a state value V(s)V(s) and per-action advantages A(s,a)A(s, a):

Q(s,a)=V(s)+A(s,a)−1∣A∣∑a′A(s,a′).Q(s, a) = V(s) + A(s, a) - \tfrac{1}{|A|}\sum_{a'} A(s, a').

Subtracting the mean pins down the split: otherwise any constant could move between VV and AA. In the reference's example, adding 7 to every advantage leaves the Q-values unchanged, and the first state's come out as 1, 2 and 3.

05

Exploring while learning

Explore

EExplorable · The bandit race

How much does it cost to keep testing, and can you shift traffic while you learn?

Which policy will give up the fewest conversions over this many users?

How sure?
0.12
0.020
3
500
0.10
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

A bandit is an MDP with one state: every round, pick an arm. Compare ε-greedy, the exploration rule DQN uses, with the other strategies, and watch regret pile up while ε stays high. DQN lowers ε over its exploration period for the same reason.

06

Run it: the network's opinion of itself

In the app
Online policy learning (DQN)Recorded · Python and R agreeRecorded 2026-11-25 · 17 values compared
R

A deep Q-network trained for 720 steps (24 episodes) in Admission control earns 0.184 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 3.085, discount 0.95).

Learned policy value (exact)
0.1840
Optimal policy value
3.269
Regret
3.085
Share of the optimal gain
−0.9064

Plots

Return per episode while trainingDoes the learned policy get closer to the best possible return as training goes on?
View data
CurveEnvironment stepsReturn per episode
Learned policy (exact)1201.435
Learned policy (exact)2401.435
Learned policy (exact)3601.435
Learned policy (exact)4800.6682
Learned policy (exact)6000.1840
Learned policy (exact)7200.1840
Training episodes1201.467
Training episodes2401.925
Training episodes3601.090
Training episodes4803.135
Training episodes600−1.305
Training episodes7203.426
Actions by state: learned vs optimalHow often does the learned policy choose each action, compared with the best policy?
View data
ActionShare of statesPolicy
accept0.7143Learned
reject0.2857Learned
accept0.2857Optimal
reject0.7143Optimal

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (DQN)0.18403.085
Optimal policy3.2690
Random actions1.6511.618

Learned policy by state (7 states)

statequeueLearned actionOptimal actionQ(accept)Q(reject)
queue 00acceptaccept1.6471.248
queue 11acceptreject1.0020.5705
queue 22acceptreject0.0186−0.2539
queue 33acceptreject−0.2849−1.078
queue 44acceptreject0.3836−0.5381
queue 55rejectreject0.15210.5791
queue 66rejectaccept−0.31890.0582

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
1120411.4671.4351.0880.0299
224080.70001.9251.4351.1310.0277
3360120.40001.0901.4351.3530.0194
4480160.10003.1350.66821.4230.0174
5600200.1000−1.3050.18401.5960.0433
6720240.10003.4260.18401.6470.0398
  • The learned policy gets only -91% of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.
  • An earlier round's policy (round 1) was better (1.435) than the final one: deep Q-learning can drift; the result keeps the final policy.
  • The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
  • Deep Q-network; Admission control (7 states, 2 actions, episodes of up to 30 steps, discount 0.95); 6 rounds × 120 steps, 25 updates of 64 replayed transitions per round (buffer 500), hidden layers 32, learning rate 0.001, ε 1 → 0.1 over 50% of the rounds, double targets, dueling head, huber loss; seed 42. Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Online policy learning with a deep Q-network (DQN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_dqn 1.0.0 · spec fa41b65540d09bf1
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_rl_*(): twins of codesplash.decide.online_rl (shared stream through the environment, exact evaluation)

# %% Inputs
# Environment "queue", discount 0.95: the app writes both into the environment files read below.
rounds <- as.integer(6)
steps <- as.integer(120)
updates <- as.integer(25)
batch_size <- as.integer(64)
buffer <- as.integer(500)
hidden <- as.integer(unlist(c(32)))
lr <- as.numeric(0.001)
encoding <- "one_hot" # one_hot | features
eps_start <- as.numeric(1)
eps_end <- as.numeric(0.1)
explore <- as.numeric(0.5)
double <- TRUE
dueling <- TRUE
loss_kind <- "huber" # huber | squared
seed <- 42
warnings <- list()

# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env <- cs_rl_read_mdp("target/academy-parity/run-98732/decide.rl_dqn/queue-dueling/out-r")
meta <- env$meta
S <- env$S; K <- env$K; gamma <- env$gamma

# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-98732/decide.rl_dqn/queue-dueling/out-r")

# %% Train online
fit <- cs_rl_dqn(env, encoding, hidden, rounds, steps, updates, batch_size, buffer, lr, eps_start, eps_end, explore, double, dueling,
                 loss_kind, seed)
trace <- fit$trace
policy <- fit$policy
sc <- cs_rl_scores(env, policy)
greedy_values <- vapply(trace, function(t) t$greedy_value, numeric(1))
best <- which.max(greedy_values)
final_return <- trace[[length(trace)]]$train_return
if (K == 1L) {
  warnings[[length(warnings) + 1L]] <- "The environment has one action, so every policy is the same and the share of the optimal gain is undefined."
}
if (fit$episodes == 0L) {
  warnings[[length(warnings) + 1L]] <- "No episode finished during training: raise the steps per round or the number of rounds."
}
if (!is.null(sc$share) && sc$share < 0.5) {
  warnings[[length(warnings) + 1L]] <- sprintf("The learned policy gets only %.0f%% of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.", 100 * sc$share)
}
if (greedy_values[best] > sc$value + 1e-9 * max(1, abs(sc$value))) {
  warnings[[length(warnings) + 1L]] <- sprintf("An earlier round's policy (round %d) was better (%s) than the final one: deep Q-learning can drift; the result keeps the final policy.",
                                              trace[[best]]$round, format(signif(greedy_values[best], 4)))
}
warnings[[length(warnings) + 1L]] <- "The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it."

# %% Result
opt_value <- as.numeric(meta$optimal_value)
uni_value <- as.numeric(meta$uniform_value)
labels <- env$labels
actions <- env$actions
live <- which(!env$terminal)
optimal <- as.integer(meta$optimal_policy) + 1L
fmt3 <- function(x) formatC(x, format = "f", digits = 3)
summary <- sprintf("A deep Q-network trained for %s steps (%s episodes) in %s earns %s per episode against %s for the optimal policy and %s for random actions (regret %s, discount %s).",
                   format(fit$env_steps, big.mark = ","), format(fit$episodes, big.mark = ","), meta$title, fmt3(sc$value), fmt3(opt_value),
                   fmt3(uni_value), fmt3(sc$regret), format(gamma, digits = 15))
values <- list(policy_value = sc$value, optimal_value = opt_value, uniform_value = uni_value, regret = sc$regret, optimal_share = sc$share,
               optimal_actions = sc$optimal_actions, best_value = greedy_values[best], best_round = trace[[best]]$round,
               final_return = final_return, estimated_value = trace[[length(trace)]]$estimated_value, n_episodes = fit$episodes,
               env_steps = fit$env_steps, rounds_run = length(trace), final_loss = trace[[length(trace)]]$loss, n_states = S, n_actions = K,
               algorithm = "dqn")
fnames <- as.character(meta$feature_names)
pol_cols <- list(list(key = "s1", label = "state", type = "string"))
for (j in seq_along(fnames)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("f%d", j), label = fnames[j], type = "number")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "optimal", label = "Optimal action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("Q(%s)", actions[j]), type = "number")
pol_df <- data.frame(s1 = labels[live], stringsAsFactors = FALSE)
for (j in seq_along(fnames)) pol_df[[sprintf("f%d", j)]] <- as.numeric(env$features[live, j])
pol_df$action <- actions[policy[live]]
pol_df$optimal <- actions[optimal[live]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(fit$q[live, j])
eval_df <- data.frame(policy = c("Learned policy (DQN)", "Optimal policy", "Random actions"), value = c(sc$value, opt_value, uni_value),
                      regret = c(sc$regret, 0, opt_value - uni_value))
share_df <- data.frame(action = actions,
                       learned = vapply(seq_len(K), function(j) if (length(live)) mean(policy[live] == j) else 0, numeric(1)),
                       optimal = vapply(seq_len(K), function(j) if (length(live)) mean(optimal[live] == j) else 0, numeric(1)))
num_or_na <- function(x) if (is.null(x)) NA_real_ else as.numeric(x)
train_df <- data.frame(round = vapply(trace, function(t) as.integer(t$round), integer(1)),
                       env_steps = vapply(trace, function(t) as.integer(t$env_steps), integer(1)),
                       episodes = vapply(trace, function(t) as.integer(t$episodes), integer(1)),
                       epsilon = vapply(trace, function(t) as.numeric(t$epsilon), numeric(1)),
                       train_return = vapply(trace, function(t) num_or_na(t$train_return), numeric(1)),
                       greedy_value = greedy_values,
                       estimated_value = vapply(trace, function(t) as.numeric(t$estimated_value), numeric(1)),
                       loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)))
has_ret <- !is.na(train_df$train_return)
curve_x <- c(train_df$env_steps, train_df$env_steps[has_ret])
curve_y <- c(train_df$greedy_value, train_df$train_return[has_ret])
curve_s <- c(rep("Learned policy (exact)", nrow(train_df)), rep("Training episodes", sum(has_ret)))
charts <- list(
  cs_chart("training", "return-curve", "Return per episode while training", list(
    x = cs_col("Environment steps", curve_x),
    y = cs_col("Return per episode", curve_y),
    series = cs_col("Curve", curve_s, levels = c("Learned policy (exact)", "Training episodes"))
  ), controls = list(reference = opt_value), question = "Does the learned policy get closer to the best possible return as training goes on?"),
  cs_chart("actions", "share-compare", "Actions by state: learned vs optimal", list(
    level = cs_col("Action", c(actions, actions), levels = actions),
    share = cs_col("Share of states", c(share_df$learned, share_df$optimal)),
    source = cs_col("Policy", c(rep("Learned", K), rep("Optimal", K)), levels = c("Learned", "Optimal"))
  ), question = "How often does the learned policy choose each action, compared with the best policy?")
)
cs_publish(list(
  method = "decide.rl_dqn",
  methodVersion = "1.0.0",
  title = "Online policy learning (DQN)",
  engine = cs_engine_info("codesplashr", "torch"),
  n = fit$env_steps,
  summary = summary,
  statistics = list(
    list(key = "policy_value", label = "Learned policy value (exact)", value = sc$value),
    list(key = "optimal_value", label = "Optimal policy value", value = opt_value),
    list(key = "regret", label = "Regret", value = sc$regret),
    list(key = "optimal_share", label = "Share of the optimal gain", value = sc$share)
  ),
  tables = list(
    list(key = "evaluation", title = "Exact return per episode",
         columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "value", label = "Return per episode", type = "number"),
                        list(key = "regret", label = "Regret", type = "number")),
         rows = eval_df),
    list(key = "policy", title = sprintf("Learned policy by state (%d states)", length(live)), columns = pol_cols, rows = pol_df),
    list(key = "training", title = "Training by round",
         columns = list(list(key = "round", label = "Round", type = "integer"), list(key = "env_steps", label = "Environment steps", type = "integer"),
                        list(key = "episodes", label = "Episodes", type = "integer"), list(key = "epsilon", label = "Exploration (ε)", type = "number"),
                        list(key = "train_return", label = "Training return", type = "number"),
                        list(key = "greedy_value", label = "Learned policy value (exact)", type = "number"),
                        list(key = "estimated_value", label = "Network's start value", type = "number"), list(key = "loss", label = "Loss", type = "number")),
         rows = train_df)
  ),
  warnings = warnings,
  notes = list(paste0(
    sprintf("Deep Q-network; %s (%d states, %d actions, episodes of up to %d steps, discount %s); ", meta$title, S, K, env$horizon, format(gamma, digits = 15)),
    sprintf("%d rounds × %d steps, %d updates of %d replayed transitions per round (buffer %d), hidden layers %s, learning rate %s, ", rounds, steps,
            updates, batch_size, buffer, paste(hidden, collapse = ", "), format(lr, digits = 15)),
    sprintf("ε %s → %s over %.0f%% of the rounds%s%s, %s loss; seed %s. ", format(eps_start, digits = 15), format(eps_end, digits = 15), 100 * explore,
            if (isTRUE(double)) ", double targets" else "", if (isTRUE(dueling)) ", dueling head" else "", loss_kind, seed),
    "Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns ",
    "per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal ",
    "policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes."
  )),
  values = values,
  charts = charts
))
Python

A deep Q-network trained for 720 steps (24 episodes) in Admission control earns 0.184 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 3.085, discount 0.95).

Learned policy value (exact)
0.1840
Optimal policy value
3.269
Regret
3.085
Share of the optimal gain
−0.9064

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

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (DQN)0.18403.085
Optimal policy3.2690
Random actions1.6511.618

Learned policy by state (7 states)

statequeueLearned actionOptimal actionQ(accept)Q(reject)
queue 00acceptaccept1.6471.248
queue 11acceptreject1.0020.5705
queue 22acceptreject0.0186−0.2539
queue 33acceptreject−0.2849−1.078
queue 44acceptreject0.3836−0.5381
queue 55rejectreject0.15210.5791
queue 66rejectaccept−0.31890.0582

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
1120411.4671.4351.0880.0299
224080.70001.9251.4351.1310.0277
3360120.40001.0901.4351.3530.0194
4480160.10003.1350.66821.4230.0174
5600200.1000−1.3050.18401.5960.0433
6720240.10003.4260.18401.6470.0398
  • The learned policy gets only -91% of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.
  • An earlier round's policy (round 1) was better (1.435) than the final one: deep Q-learning can drift; the result keeps the final policy.
  • The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
  • Deep Q-network; Admission control (7 states, 2 actions, episodes of up to 30 steps, discount 0.95); 6 rounds × 120 steps, 25 updates of 64 replayed transitions per round (buffer 500), hidden layers 32, learning rate 0.001, ε 1 → 0.1 over 50% of the rounds, double targets, dueling head, huber loss; seed 42. Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Online policy learning with a deep Q-network (DQN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_dqn 1.0.0 · spec fa41b65540d09bf1
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np

import codesplash as cs
from codesplash.decide import online_rl as rl  # twin of codesplashr::cs_rl_* (shared stream through the environment, exact evaluation)

# %% Inputs
# Environment "queue", discount 0.95: the app writes both into the environment files read below.
rounds = int(6)
steps = int(120)
updates = int(25)
batch_size = int(64)
buffer = int(500)
hidden = [int(u) for u in [32]]
lr = float(0.001)
encoding = "one_hot"  # one_hot | features
eps_start = float(1)
eps_end = float(0.1)
explore = float(0.5)
double = True
dueling = True
loss_kind = "huber"  # huber | squared
seed = 42
warnings = []

# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env = rl.read_mdp("target/academy-parity/run-98732/decide.rl_dqn/queue-dueling/out-python")
meta = env["meta"]
S, K, gamma = env["S"], env["K"], env["gamma"]

from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-98732/decide.rl_dqn/queue-dueling/out-python",
)

# %% Train online
fit = rl.dqn(env, encoding, hidden, rounds, steps, updates, batch_size, buffer, lr, eps_start, eps_end, explore, double, dueling, loss_kind, seed)
trace = fit["trace"]
policy = fit["policy"]
sc = rl.scores(env, policy)
best = max(range(len(trace)), key=lambda i: (trace[i]["greedy_value"], -i))
final_return = trace[-1]["train_return"]
if K == 1:
    warnings.append("The environment has one action, so every policy is the same and the share of the optimal gain is undefined.")
if fit["episodes"] == 0:
    warnings.append("No episode finished during training: raise the steps per round or the number of rounds.")
if sc["share"] is not None and sc["share"] < 0.5:
    warnings.append(f"The learned policy gets only {sc['share']:.0%} of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.")
if trace[best]["greedy_value"] > sc["value"] + 1e-9 * max(1.0, abs(sc["value"])):
    warnings.append(f"An earlier round's policy (round {trace[best]['round']}) was better ({trace[best]['greedy_value']:.4g}) than the final one: deep Q-learning can drift; the result keeps the final policy.")
warnings.append("The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.")

# %% Result
opt_value, uni_value = float(meta["optimal_value"]), float(meta["uniform_value"])
labels, actions = env["labels"], env["actions"]
qs = rl.q_star(env)
live = [s for s in range(S) if not env["terminal"][s]]
optimal = meta["optimal_policy"]
summary = (
    f"A deep Q-network trained for {fit['env_steps']:,} steps ({fit['episodes']:,} episodes) in {meta['title']} earns {sc['value']:.3f} per episode "
    f"against {opt_value:.3f} for the optimal policy and {uni_value:.3f} for random actions (regret {sc['regret']:.3f}, discount {gamma:g})."
)
values = {
    "policy_value": sc["value"], "optimal_value": opt_value, "uniform_value": uni_value, "regret": sc["regret"], "optimal_share": sc["share"],
    "optimal_actions": sc["optimal_actions"], "best_value": trace[best]["greedy_value"], "best_round": trace[best]["round"], "final_return": final_return,
    "estimated_value": trace[-1]["estimated_value"], "n_episodes": fit["episodes"], "env_steps": fit["env_steps"], "rounds_run": len(trace),
    "final_loss": trace[-1]["loss"], "n_states": S, "n_actions": K, "algorithm": "dqn",
}
pol_cols = [{"key": "s1", "label": "state", "type": "string"}]
pol_cols += [{"key": f"f{j + 1}", "label": f, "type": "number"} for j, f in enumerate(meta["feature_names"])]
pol_cols += [{"key": "action", "label": "Learned action", "type": "string"}, {"key": "optimal", "label": "Optimal action", "type": "string"}]
pol_cols += [{"key": f"v{j + 1}", "label": f"Q({a})", "type": "number"} for j, a in enumerate(actions)]
pol_rows = []
for s in live:
    r = {"s1": labels[s]}
    r.update({f"f{j + 1}": float(x) for j, x in enumerate(env["features"][s])})
    r["action"] = actions[int(policy[s])]
    r["optimal"] = actions[int(optimal[s])]
    r.update({f"v{j + 1}": float(fit["q"][s, j]) for j in range(K)})
    pol_rows.append(r)
eval_rows = [
    {"policy": "Learned policy (DQN)", "value": sc["value"], "regret": sc["regret"]},
    {"policy": "Optimal policy", "value": opt_value, "regret": 0.0},
    {"policy": "Random actions", "value": uni_value, "regret": opt_value - uni_value},
]
share_rows = [{"action": a, "learned": float(np.mean([int(policy[s]) == j for s in live])) if live else 0.0,
               "optimal": float(np.mean([int(optimal[s]) == j for s in live])) if live else 0.0} for j, a in enumerate(actions)]
curve_x = [t["env_steps"] for t in trace]
curve_rows = [(x, t["greedy_value"], "Learned policy (exact)") for x, t in zip(curve_x, trace)]
curve_rows += [(x, t["train_return"], "Training episodes") for x, t in zip(curve_x, trace) if t["train_return"] is not None]
charts = [
    cs.chart("training", "return-curve", "Return per episode while training", {
        "x": cs.col("Environment steps", [r[0] for r in curve_rows]),
        "y": cs.col("Return per episode", [r[1] for r in curve_rows]),
        "series": cs.col("Curve", [r[2] for r in curve_rows], levels=["Learned policy (exact)", "Training episodes"]),
    }, controls={"reference": opt_value}, question="Does the learned policy get closer to the best possible return as training goes on?"),
    cs.chart("actions", "share-compare", "Actions by state: learned vs optimal", {
        "level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=actions),
        "share": cs.col("Share of states", [r["learned"] for r in share_rows] + [r["optimal"] for r in share_rows]),
        "source": cs.col("Policy", ["Learned"] * K + ["Optimal"] * K, levels=["Learned", "Optimal"]),
    }, question="How often does the learned policy choose each action, compared with the best policy?"),
]
cs.publish({
    "method": "decide.rl_dqn",
    "methodVersion": "1.0.0",
    "title": "Online policy learning (DQN)",
    "engine": cs.engine_info("numpy", "pandas", "torch"),
    "n": fit["env_steps"],
    "summary": summary,
    "statistics": [
        {"key": "policy_value", "label": "Learned policy value (exact)", "value": sc["value"]},
        {"key": "optimal_value", "label": "Optimal policy value", "value": opt_value},
        {"key": "regret", "label": "Regret", "value": sc["regret"]},
        {"key": "optimal_share", "label": "Share of the optimal gain", "value": sc["share"]},
    ],
    "tables": [
        {"key": "evaluation", "title": "Exact return per episode",
         "columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "value", "label": "Return per episode", "type": "number"},
                     {"key": "regret", "label": "Regret", "type": "number"}],
         "rows": eval_rows},
        {"key": "policy", "title": f"Learned policy by state ({len(live)} states)", "columns": pol_cols, "rows": pol_rows},
        {"key": "training", "title": "Training by round",
         "columns": [{"key": "round", "label": "Round", "type": "integer"}, {"key": "env_steps", "label": "Environment steps", "type": "integer"},
                     {"key": "episodes", "label": "Episodes", "type": "integer"}, {"key": "epsilon", "label": "Exploration (ε)", "type": "number"},
                     {"key": "train_return", "label": "Training return", "type": "number"},
                     {"key": "greedy_value", "label": "Learned policy value (exact)", "type": "number"},
                     {"key": "estimated_value", "label": "Network's start value", "type": "number"}, {"key": "loss", "label": "Loss", "type": "number"}],
         "rows": trace},
    ],
    "warnings": warnings,
    "notes": [
        f"Deep Q-network; {meta['title']} ({S} states, {K} actions, episodes of up to {env['horizon']} steps, discount {gamma:g}); "
        f"{rounds} rounds × {steps} steps, {updates} updates of {batch_size} replayed transitions per round (buffer {buffer}), hidden layers "
        f"{', '.join(str(h) for h in hidden)}, learning rate {lr:g}, ε {eps_start:g} → {eps_end:g} over {explore:.0%} of the rounds"
        f"{', double targets' if double else ''}{', dueling head' if dueling else ''}, {loss_kind} loss; seed {seed}. "
        "Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns "
        "per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal "
        "policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes.",
    ],
    "values": values,
    "charts": charts,
})

This run uses double targets and a dueling head in the admission queue. The network's own estimate of its greedy policy's value is 1.647; the policy's exact value is 0.184, and random actions earn 1.651. A network's estimate of itself is not evidence. And its best round was round 1: deep Q-learning can drift after finding a good policy.

07

Run it: features and squared error

In the app
Online policy learning (DQN)Recorded · Python and R agreeRecorded 2026-11-25 · 17 values compared
R

A deep Q-network trained for 720 steps (60 episodes) in Inventory earns 29.265 per episode against 31.113 for the optimal policy and 24.166 for random actions (regret 1.848, discount 0.9).

Learned policy value (exact)
29.265
Optimal policy value
31.113
Regret
1.848
Share of the optimal gain
0.7339

Plots

Return per episode while trainingDoes the learned policy get closer to the best possible return as training goes on?
View data
CurveEnvironment stepsReturn per episode
Learned policy (exact)12028.944
Learned policy (exact)24028.944
Learned policy (exact)36030.185
Learned policy (exact)48031.113
Learned policy (exact)60025.659
Learned policy (exact)72029.265
Training episodes12024.739
Training episodes24027.563
Training episodes36026.023
Training episodes48027.308
Training episodes60025.559
Training episodes72024.981
Actions by state: learned vs optimalHow often does the learned policy choose each action, compared with the best policy?
View data
ActionShare of statesPolicy
order 00.3333Learned
order 20.3333Learned
order 40.3333Learned
order 00.5556Optimal
order 20.2222Optimal
order 40.2222Optimal

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (DQN)29.2651.848
Optimal policy31.1130
Random actions24.1666.947

Learned policy by state (9 states)

statestockLearned actionOptimal actionQ(order 0)Q(order 2)Q(order 4)
stock 00order 4order 46.8499.33510.459
stock 11order 4order 49.19710.86111.356
stock 22order 4order 210.74612.11212.298
stock 33order 2order 212.29613.36413.240
stock 44order 2order 013.63214.34514.159
stock 55order 2order 014.89215.23015.068
stock 66order 0order 016.15216.11415.978
stock 77order 0order 017.41216.99916.888
stock 88order 0order 018.67217.88417.797

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
112010124.73928.9445.7670.0114
2240200.472227.56328.9445.1260.0063
3360300.050026.02330.1859.7200.0068
4480400.050027.30831.1139.3640.0064
5600500.050025.55925.65913.1160.0082
6720600.050024.98129.26512.2980.0064
  • An earlier round's policy (round 4) was better (31.11) than the final one: deep Q-learning can drift; the result keeps the final policy.
  • The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
  • Deep Q-network; Inventory (9 states, 3 actions, episodes of up to 12 steps, discount 0.9); 6 rounds × 120 steps, 25 updates of 32 replayed transitions per round (buffer 10000), hidden layers 16, 16, learning rate 0.003, ε 1 → 0.05 over 30% of the rounds, squared loss; seed 42. Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Online policy learning with a deep Q-network (DQN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_dqn 1.0.0 · spec 20342959c3a0a7e0
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_rl_*(): twins of codesplash.decide.online_rl (shared stream through the environment, exact evaluation)

# %% Inputs
# Environment "inventory", discount 0.9: the app writes both into the environment files read below.
rounds <- as.integer(6)
steps <- as.integer(120)
updates <- as.integer(25)
batch_size <- as.integer(32)
buffer <- as.integer(10000)
hidden <- as.integer(unlist(c(16, 16)))
lr <- as.numeric(0.003)
encoding <- "features" # one_hot | features
eps_start <- as.numeric(1)
eps_end <- as.numeric(0.05)
explore <- as.numeric(0.3)
double <- FALSE
dueling <- FALSE
loss_kind <- "squared" # huber | squared
seed <- 42
warnings <- list()

# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env <- cs_rl_read_mdp("target/academy-parity/run-98732/decide.rl_dqn/inventory-features-squared/out-r")
meta <- env$meta
S <- env$S; K <- env$K; gamma <- env$gamma

# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-98732/decide.rl_dqn/inventory-features-squared/out-r")

# %% Train online
fit <- cs_rl_dqn(env, encoding, hidden, rounds, steps, updates, batch_size, buffer, lr, eps_start, eps_end, explore, double, dueling,
                 loss_kind, seed)
trace <- fit$trace
policy <- fit$policy
sc <- cs_rl_scores(env, policy)
greedy_values <- vapply(trace, function(t) t$greedy_value, numeric(1))
best <- which.max(greedy_values)
final_return <- trace[[length(trace)]]$train_return
if (K == 1L) {
  warnings[[length(warnings) + 1L]] <- "The environment has one action, so every policy is the same and the share of the optimal gain is undefined."
}
if (fit$episodes == 0L) {
  warnings[[length(warnings) + 1L]] <- "No episode finished during training: raise the steps per round or the number of rounds."
}
if (!is.null(sc$share) && sc$share < 0.5) {
  warnings[[length(warnings) + 1L]] <- sprintf("The learned policy gets only %.0f%% of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.", 100 * sc$share)
}
if (greedy_values[best] > sc$value + 1e-9 * max(1, abs(sc$value))) {
  warnings[[length(warnings) + 1L]] <- sprintf("An earlier round's policy (round %d) was better (%s) than the final one: deep Q-learning can drift; the result keeps the final policy.",
                                              trace[[best]]$round, format(signif(greedy_values[best], 4)))
}
warnings[[length(warnings) + 1L]] <- "The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it."

# %% Result
opt_value <- as.numeric(meta$optimal_value)
uni_value <- as.numeric(meta$uniform_value)
labels <- env$labels
actions <- env$actions
live <- which(!env$terminal)
optimal <- as.integer(meta$optimal_policy) + 1L
fmt3 <- function(x) formatC(x, format = "f", digits = 3)
summary <- sprintf("A deep Q-network trained for %s steps (%s episodes) in %s earns %s per episode against %s for the optimal policy and %s for random actions (regret %s, discount %s).",
                   format(fit$env_steps, big.mark = ","), format(fit$episodes, big.mark = ","), meta$title, fmt3(sc$value), fmt3(opt_value),
                   fmt3(uni_value), fmt3(sc$regret), format(gamma, digits = 15))
values <- list(policy_value = sc$value, optimal_value = opt_value, uniform_value = uni_value, regret = sc$regret, optimal_share = sc$share,
               optimal_actions = sc$optimal_actions, best_value = greedy_values[best], best_round = trace[[best]]$round,
               final_return = final_return, estimated_value = trace[[length(trace)]]$estimated_value, n_episodes = fit$episodes,
               env_steps = fit$env_steps, rounds_run = length(trace), final_loss = trace[[length(trace)]]$loss, n_states = S, n_actions = K,
               algorithm = "dqn")
fnames <- as.character(meta$feature_names)
pol_cols <- list(list(key = "s1", label = "state", type = "string"))
for (j in seq_along(fnames)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("f%d", j), label = fnames[j], type = "number")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "optimal", label = "Optimal action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("Q(%s)", actions[j]), type = "number")
pol_df <- data.frame(s1 = labels[live], stringsAsFactors = FALSE)
for (j in seq_along(fnames)) pol_df[[sprintf("f%d", j)]] <- as.numeric(env$features[live, j])
pol_df$action <- actions[policy[live]]
pol_df$optimal <- actions[optimal[live]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(fit$q[live, j])
eval_df <- data.frame(policy = c("Learned policy (DQN)", "Optimal policy", "Random actions"), value = c(sc$value, opt_value, uni_value),
                      regret = c(sc$regret, 0, opt_value - uni_value))
share_df <- data.frame(action = actions,
                       learned = vapply(seq_len(K), function(j) if (length(live)) mean(policy[live] == j) else 0, numeric(1)),
                       optimal = vapply(seq_len(K), function(j) if (length(live)) mean(optimal[live] == j) else 0, numeric(1)))
num_or_na <- function(x) if (is.null(x)) NA_real_ else as.numeric(x)
train_df <- data.frame(round = vapply(trace, function(t) as.integer(t$round), integer(1)),
                       env_steps = vapply(trace, function(t) as.integer(t$env_steps), integer(1)),
                       episodes = vapply(trace, function(t) as.integer(t$episodes), integer(1)),
                       epsilon = vapply(trace, function(t) as.numeric(t$epsilon), numeric(1)),
                       train_return = vapply(trace, function(t) num_or_na(t$train_return), numeric(1)),
                       greedy_value = greedy_values,
                       estimated_value = vapply(trace, function(t) as.numeric(t$estimated_value), numeric(1)),
                       loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)))
has_ret <- !is.na(train_df$train_return)
curve_x <- c(train_df$env_steps, train_df$env_steps[has_ret])
curve_y <- c(train_df$greedy_value, train_df$train_return[has_ret])
curve_s <- c(rep("Learned policy (exact)", nrow(train_df)), rep("Training episodes", sum(has_ret)))
charts <- list(
  cs_chart("training", "return-curve", "Return per episode while training", list(
    x = cs_col("Environment steps", curve_x),
    y = cs_col("Return per episode", curve_y),
    series = cs_col("Curve", curve_s, levels = c("Learned policy (exact)", "Training episodes"))
  ), controls = list(reference = opt_value), question = "Does the learned policy get closer to the best possible return as training goes on?"),
  cs_chart("actions", "share-compare", "Actions by state: learned vs optimal", list(
    level = cs_col("Action", c(actions, actions), levels = actions),
    share = cs_col("Share of states", c(share_df$learned, share_df$optimal)),
    source = cs_col("Policy", c(rep("Learned", K), rep("Optimal", K)), levels = c("Learned", "Optimal"))
  ), question = "How often does the learned policy choose each action, compared with the best policy?")
)
cs_publish(list(
  method = "decide.rl_dqn",
  methodVersion = "1.0.0",
  title = "Online policy learning (DQN)",
  engine = cs_engine_info("codesplashr", "torch"),
  n = fit$env_steps,
  summary = summary,
  statistics = list(
    list(key = "policy_value", label = "Learned policy value (exact)", value = sc$value),
    list(key = "optimal_value", label = "Optimal policy value", value = opt_value),
    list(key = "regret", label = "Regret", value = sc$regret),
    list(key = "optimal_share", label = "Share of the optimal gain", value = sc$share)
  ),
  tables = list(
    list(key = "evaluation", title = "Exact return per episode",
         columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "value", label = "Return per episode", type = "number"),
                        list(key = "regret", label = "Regret", type = "number")),
         rows = eval_df),
    list(key = "policy", title = sprintf("Learned policy by state (%d states)", length(live)), columns = pol_cols, rows = pol_df),
    list(key = "training", title = "Training by round",
         columns = list(list(key = "round", label = "Round", type = "integer"), list(key = "env_steps", label = "Environment steps", type = "integer"),
                        list(key = "episodes", label = "Episodes", type = "integer"), list(key = "epsilon", label = "Exploration (ε)", type = "number"),
                        list(key = "train_return", label = "Training return", type = "number"),
                        list(key = "greedy_value", label = "Learned policy value (exact)", type = "number"),
                        list(key = "estimated_value", label = "Network's start value", type = "number"), list(key = "loss", label = "Loss", type = "number")),
         rows = train_df)
  ),
  warnings = warnings,
  notes = list(paste0(
    sprintf("Deep Q-network; %s (%d states, %d actions, episodes of up to %d steps, discount %s); ", meta$title, S, K, env$horizon, format(gamma, digits = 15)),
    sprintf("%d rounds × %d steps, %d updates of %d replayed transitions per round (buffer %d), hidden layers %s, learning rate %s, ", rounds, steps,
            updates, batch_size, buffer, paste(hidden, collapse = ", "), format(lr, digits = 15)),
    sprintf("ε %s → %s over %.0f%% of the rounds%s%s, %s loss; seed %s. ", format(eps_start, digits = 15), format(eps_end, digits = 15), 100 * explore,
            if (isTRUE(double)) ", double targets" else "", if (isTRUE(dueling)) ", dueling head" else "", loss_kind, seed),
    "Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns ",
    "per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal ",
    "policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes."
  )),
  values = values,
  charts = charts
))
Python

A deep Q-network trained for 720 steps (60 episodes) in Inventory earns 29.265 per episode against 31.113 for the optimal policy and 24.166 for random actions (regret 1.848, discount 0.9).

Learned policy value (exact)
29.265
Optimal policy value
31.113
Regret
1.848
Share of the optimal gain
0.7339

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

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (DQN)29.2651.848
Optimal policy31.1130
Random actions24.1666.947

Learned policy by state (9 states)

statestockLearned actionOptimal actionQ(order 0)Q(order 2)Q(order 4)
stock 00order 4order 46.8499.33510.459
stock 11order 4order 49.19710.86111.356
stock 22order 4order 210.74612.11212.298
stock 33order 2order 212.29613.36413.240
stock 44order 2order 013.63214.34514.159
stock 55order 2order 014.89215.23015.068
stock 66order 0order 016.15216.11415.978
stock 77order 0order 017.41216.99916.888
stock 88order 0order 018.67217.88417.797

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
112010124.73928.9445.7670.0114
2240200.472227.56328.9445.1260.0063
3360300.050026.02330.1859.7200.0068
4480400.050027.30831.1139.3640.0064
5600500.050025.55925.65913.1160.0082
6720600.050024.98129.26512.2980.0064
  • An earlier round's policy (round 4) was better (31.11) than the final one: deep Q-learning can drift; the result keeps the final policy.
  • The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
  • Deep Q-network; Inventory (9 states, 3 actions, episodes of up to 12 steps, discount 0.9); 6 rounds × 120 steps, 25 updates of 32 replayed transitions per round (buffer 10000), hidden layers 16, 16, learning rate 0.003, ε 1 → 0.05 over 30% of the rounds, squared loss; seed 42. Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Online policy learning with a deep Q-network (DQN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_dqn 1.0.0 · spec 20342959c3a0a7e0
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np

import codesplash as cs
from codesplash.decide import online_rl as rl  # twin of codesplashr::cs_rl_* (shared stream through the environment, exact evaluation)

# %% Inputs
# Environment "inventory", discount 0.9: the app writes both into the environment files read below.
rounds = int(6)
steps = int(120)
updates = int(25)
batch_size = int(32)
buffer = int(10000)
hidden = [int(u) for u in [16, 16]]
lr = float(0.003)
encoding = "features"  # one_hot | features
eps_start = float(1)
eps_end = float(0.05)
explore = float(0.3)
double = False
dueling = False
loss_kind = "squared"  # huber | squared
seed = 42
warnings = []

# %% Environment: written by the app before the run (mdp/transitions.parquet + mdp/mdp.json in the run folder)
env = rl.read_mdp("target/academy-parity/run-98732/decide.rl_dqn/inventory-features-squared/out-python")
meta = env["meta"]
S, K, gamma = env["S"], env["K"], env["gamma"]

from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-98732/decide.rl_dqn/inventory-features-squared/out-python",
)

# %% Train online
fit = rl.dqn(env, encoding, hidden, rounds, steps, updates, batch_size, buffer, lr, eps_start, eps_end, explore, double, dueling, loss_kind, seed)
trace = fit["trace"]
policy = fit["policy"]
sc = rl.scores(env, policy)
best = max(range(len(trace)), key=lambda i: (trace[i]["greedy_value"], -i))
final_return = trace[-1]["train_return"]
if K == 1:
    warnings.append("The environment has one action, so every policy is the same and the share of the optimal gain is undefined.")
if fit["episodes"] == 0:
    warnings.append("No episode finished during training: raise the steps per round or the number of rounds.")
if sc["share"] is not None and sc["share"] < 0.5:
    warnings.append(f"The learned policy gets only {sc['share']:.0%} of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.")
if trace[best]["greedy_value"] > sc["value"] + 1e-9 * max(1.0, abs(sc["value"])):
    warnings.append(f"An earlier round's policy (round {trace[best]['round']}) was better ({trace[best]['greedy_value']:.4g}) than the final one: deep Q-learning can drift; the result keeps the final policy.")
warnings.append("The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.")

# %% Result
opt_value, uni_value = float(meta["optimal_value"]), float(meta["uniform_value"])
labels, actions = env["labels"], env["actions"]
qs = rl.q_star(env)
live = [s for s in range(S) if not env["terminal"][s]]
optimal = meta["optimal_policy"]
summary = (
    f"A deep Q-network trained for {fit['env_steps']:,} steps ({fit['episodes']:,} episodes) in {meta['title']} earns {sc['value']:.3f} per episode "
    f"against {opt_value:.3f} for the optimal policy and {uni_value:.3f} for random actions (regret {sc['regret']:.3f}, discount {gamma:g})."
)
values = {
    "policy_value": sc["value"], "optimal_value": opt_value, "uniform_value": uni_value, "regret": sc["regret"], "optimal_share": sc["share"],
    "optimal_actions": sc["optimal_actions"], "best_value": trace[best]["greedy_value"], "best_round": trace[best]["round"], "final_return": final_return,
    "estimated_value": trace[-1]["estimated_value"], "n_episodes": fit["episodes"], "env_steps": fit["env_steps"], "rounds_run": len(trace),
    "final_loss": trace[-1]["loss"], "n_states": S, "n_actions": K, "algorithm": "dqn",
}
pol_cols = [{"key": "s1", "label": "state", "type": "string"}]
pol_cols += [{"key": f"f{j + 1}", "label": f, "type": "number"} for j, f in enumerate(meta["feature_names"])]
pol_cols += [{"key": "action", "label": "Learned action", "type": "string"}, {"key": "optimal", "label": "Optimal action", "type": "string"}]
pol_cols += [{"key": f"v{j + 1}", "label": f"Q({a})", "type": "number"} for j, a in enumerate(actions)]
pol_rows = []
for s in live:
    r = {"s1": labels[s]}
    r.update({f"f{j + 1}": float(x) for j, x in enumerate(env["features"][s])})
    r["action"] = actions[int(policy[s])]
    r["optimal"] = actions[int(optimal[s])]
    r.update({f"v{j + 1}": float(fit["q"][s, j]) for j in range(K)})
    pol_rows.append(r)
eval_rows = [
    {"policy": "Learned policy (DQN)", "value": sc["value"], "regret": sc["regret"]},
    {"policy": "Optimal policy", "value": opt_value, "regret": 0.0},
    {"policy": "Random actions", "value": uni_value, "regret": opt_value - uni_value},
]
share_rows = [{"action": a, "learned": float(np.mean([int(policy[s]) == j for s in live])) if live else 0.0,
               "optimal": float(np.mean([int(optimal[s]) == j for s in live])) if live else 0.0} for j, a in enumerate(actions)]
curve_x = [t["env_steps"] for t in trace]
curve_rows = [(x, t["greedy_value"], "Learned policy (exact)") for x, t in zip(curve_x, trace)]
curve_rows += [(x, t["train_return"], "Training episodes") for x, t in zip(curve_x, trace) if t["train_return"] is not None]
charts = [
    cs.chart("training", "return-curve", "Return per episode while training", {
        "x": cs.col("Environment steps", [r[0] for r in curve_rows]),
        "y": cs.col("Return per episode", [r[1] for r in curve_rows]),
        "series": cs.col("Curve", [r[2] for r in curve_rows], levels=["Learned policy (exact)", "Training episodes"]),
    }, controls={"reference": opt_value}, question="Does the learned policy get closer to the best possible return as training goes on?"),
    cs.chart("actions", "share-compare", "Actions by state: learned vs optimal", {
        "level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=actions),
        "share": cs.col("Share of states", [r["learned"] for r in share_rows] + [r["optimal"] for r in share_rows]),
        "source": cs.col("Policy", ["Learned"] * K + ["Optimal"] * K, levels=["Learned", "Optimal"]),
    }, question="How often does the learned policy choose each action, compared with the best policy?"),
]
cs.publish({
    "method": "decide.rl_dqn",
    "methodVersion": "1.0.0",
    "title": "Online policy learning (DQN)",
    "engine": cs.engine_info("numpy", "pandas", "torch"),
    "n": fit["env_steps"],
    "summary": summary,
    "statistics": [
        {"key": "policy_value", "label": "Learned policy value (exact)", "value": sc["value"]},
        {"key": "optimal_value", "label": "Optimal policy value", "value": opt_value},
        {"key": "regret", "label": "Regret", "value": sc["regret"]},
        {"key": "optimal_share", "label": "Share of the optimal gain", "value": sc["share"]},
    ],
    "tables": [
        {"key": "evaluation", "title": "Exact return per episode",
         "columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "value", "label": "Return per episode", "type": "number"},
                     {"key": "regret", "label": "Regret", "type": "number"}],
         "rows": eval_rows},
        {"key": "policy", "title": f"Learned policy by state ({len(live)} states)", "columns": pol_cols, "rows": pol_rows},
        {"key": "training", "title": "Training by round",
         "columns": [{"key": "round", "label": "Round", "type": "integer"}, {"key": "env_steps", "label": "Environment steps", "type": "integer"},
                     {"key": "episodes", "label": "Episodes", "type": "integer"}, {"key": "epsilon", "label": "Exploration (ε)", "type": "number"},
                     {"key": "train_return", "label": "Training return", "type": "number"},
                     {"key": "greedy_value", "label": "Learned policy value (exact)", "type": "number"},
                     {"key": "estimated_value", "label": "Network's start value", "type": "number"}, {"key": "loss", "label": "Loss", "type": "number"}],
         "rows": trace},
    ],
    "warnings": warnings,
    "notes": [
        f"Deep Q-network; {meta['title']} ({S} states, {K} actions, episodes of up to {env['horizon']} steps, discount {gamma:g}); "
        f"{rounds} rounds × {steps} steps, {updates} updates of {batch_size} replayed transitions per round (buffer {buffer}), hidden layers "
        f"{', '.join(str(h) for h in hidden)}, learning rate {lr:g}, ε {eps_start:g} → {eps_end:g} over {explore:.0%} of the rounds"
        f"{', double targets' if double else ''}{', dueling head' if dueling else ''}, {loss_kind} loss; seed {seed}. "
        "Rewards are divided by the environment's largest absolute reward while learning. Values are exact expected discounted returns "
        "per episode over the episode length from the start state (backward recursion over the environment's transition table); the optimal "
        "policy comes from value iteration on the same table. The training return is the observed average over the round's finished episodes.",
    ],
    "values": values,
    "charts": charts,
})

Here the state enters as scaled features, so nearby stock levels share what's learned, with plain targets and squared error. The learned policy reaches 73.4% of the optimal gain; an earlier round was better again.

Offline, decide.offline_rl offers the same Double Q targets and Dueling head options for its Q-learning modes:

Offline policy learning (Conservative Q-learning)Recorded · Python and R agreeRecorded 2026-11-25 · 15 values compared
R

Conservative Q-learning learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.295, 95% CI [0.255, 0.341], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 59% of the logged states.

Learned policy value (FQE)
0.2946
95% CI
[0.2554, 0.3409]
Logged policy value
0.0487
Agreement with logged actions
0.5891

Plots

Estimated return per episodeHow large are several estimates, how precise, and which exclude the null?
View data
ValueUpperPolicy and estimatorLower
0.29460.3409Conservative Q-learning · Fitted Q evaluation0.2554
0.51200.5317Behavior cloning (baseline) · Fitted Q evaluation0.4939
0.04870.1387Logged policy · Observed return−0.0376
Estimated start-state value by iterationHow does a policy's return change as training goes on, and does it beat the policy that logged the data?
View data
IterationEstimated value
10.7110
20.7527
30.6095
Action shares: logged vs learnedHow often does the learned policy choose each action, compared with the logged policy?
View data
ActionSharePolicy
left0.1688Logged
stay0.1906Logged
right0.6406Logged
left0.2000Learned
stay0Learned
right0.8000Learned

Estimated return per episode

PolicyEstimatorEstimate95% CI low95% CI high
Conservative Q-learningFitted Q evaluation0.29460.25540.3409
Behavior cloning (baseline)Fitted Q evaluation0.51200.49390.5317
Logged policyObserved return0.0487−0.03760.1387

Learned policy by state (12 of 12 distinct states)

positionweather todayLearned actionQ(left)Q(stay)Q(right)
1sunright0.28280.10790.4264
2sunright0.10120.19710.6267
3rainright0.31410.27170.6001
4rainright0.42330.58390.9480
5rainright0.54930.89911.274
1rainleft0.73880.24240.6814
0sunright0.06160.49050.5717
3sunright0.09390.46400.9343
2rainleft0.47570.04160.4155
4sunright0.08740.75411.220
5sunright0.07941.0271.509
0rainleft0.95310.67820.8639

Actions: logged vs learned policy

actionLogged shareLearned share
left16.9%20.0%
stay19.1%0.0%
right64.1%80.0%

Training by iteration

IterationLossEstimated start-state value
10.67420.7110
20.60120.7527
30.54470.6095
  • 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.
  • 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.
  • Conservative Q-learning; discount 0.95; Q-models and evaluation use position, weather today (networks: hidden layers 8, 8, 3 rounds × 5 epochs, learning rate 0.005). Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds); 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact R script · R 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 3d43d3ac975a68f8
# 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", "position", "weather today", "action", "reward", "done")))
n_input <- nrow(df)
df[["weather today"]] <- factor(df[["weather today"]], levels = c("rain", "sun"))  # stored level order
df[["action"]] <- factor(df[["action"]], levels = c("left", "stay", "right"))  # stored level order
df[["done"]] <- factor(df[["done"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("episode", "step", "position", "weather today", "action", "reward", "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", "position", "weather today", "action", "reward", "done"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col <- "episode"
step_col <- "step"
a_col <- "action"
r_col <- "reward"
p_col <- NULL
done_col <- "done"
features <- c("position", "weather today")
algorithm <- "cql" # fqi | bc | cql | iql
gamma <- as.numeric(0.95)
iterations <- as.integer(300)
rounds <- as.integer(3)
hidden <- as.integer(unlist(c(8, 8)))
epochs <- as.integer(5)
lr <- as.numeric(0.005)
batch_size <- 256
alpha <- as.numeric(0.5)
double <- FALSE
dueling <- TRUE
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

# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-98732/decide.offline_rl/corridor-cql-dueling-single/out-r")

# %% 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", "torch"),
  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
))
Python

Conservative Q-learning learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.295, 95% CI [0.255, 0.341], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 59% of the logged states.

Learned policy value (FQE)
0.2946
95% CI
[0.2554, 0.3409]
Logged policy value
0.0487
Agreement with logged actions
0.5891

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

Estimated return per episode

PolicyEstimatorEstimate95% CI low95% CI high
Conservative Q-learningFitted Q evaluation0.29460.25540.3409
Behavior cloning (baseline)Fitted Q evaluation0.51200.49390.5317
Logged policyObserved return0.0487−0.03760.1387

Learned policy by state (12 of 12 distinct states)

positionweather todayLearned actionQ(left)Q(stay)Q(right)
1sunright0.28280.10790.4264
2sunright0.10120.19710.6267
3rainright0.31410.27170.6001
4rainright0.42330.58390.9480
5rainright0.54930.89911.274
1rainleft0.73880.24240.6814
0sunright0.06160.49050.5717
3sunright0.09390.46400.9343
2rainleft0.47570.04160.4155
4sunright0.08740.75411.220
5sunright0.07941.0271.509
0rainleft0.95310.67820.8639

Actions: logged vs learned policy

actionLogged shareLearned share
left16.9%20.0%
stay19.1%0.0%
right64.1%80.0%

Training by iteration

IterationLossEstimated start-state value
10.67420.7110
20.60120.7527
30.54470.6095
  • 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.
  • 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.
  • Conservative Q-learning; discount 0.95; Q-models and evaluation use position, weather today (networks: hidden layers 8, 8, 3 rounds × 5 epochs, learning rate 0.005). Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds); 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact Python script · Python 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 3d43d3ac975a68f8
# 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)
from codesplash.decide import offline_rl as orl  # twin of codesplashr::cs_orl_* (shared initial weights and batch order)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "position", "weather today", "action", "reward", "done"])
n_input = len(df)
df["weather today"] = pd.Categorical(df["weather today"], categories=["rain", "sun"])  # stored level order
df["action"] = pd.Categorical(df["action"], categories=["left", "stay", "right"])  # stored level order
df["done"] = pd.Categorical(df["done"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["episode", "step", "position", "weather today", "action", "reward", "done"])  # listwise deletion over the analysis columns
df["weather today"] = df["weather today"].cat.remove_unused_categories()
df["action"] = df["action"].cat.remove_unused_categories()
df["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", "position", "weather today", "action", "reward", "done"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col, step_col, a_col, r_col = "episode", "step", "action", "reward"
p_col = None
done_col = "done"
features = ["position", "weather today"]
algorithm = "cql"  # fqi | bc | cql | iql
gamma = float(0.95)
iterations = int(300)
rounds = int(3)
hidden = [int(u) for u in [8, 8]]
epochs = int(5)
lr = float(0.005)
batch_size = 256
alpha = float(0.5)
double = False
dueling = True
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"]

from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-98732/decide.offline_rl/corridor-cql-dueling-single/out-python",
)

# %% 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", "torch"),
    "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,
})
08

What runs here

Read
09

Common mistakes

Read
10

Check: DQN and its fixes

Checkpoint

Check yourself

A transition ends the episode with reward −1. The target network's best next-state value is 3 and γ = 0.99. What is the DQN target?

Show the answer

Answer: -1

At a terminal step the bootstrap term is dropped: y = r = −1.

Check yourself

What problem does the target network address?

Show the answer

Answer: a

A lagging copy holds the targets still for a while. The replay buffer addresses correlated consecutive samples.

Check yourself

Why sample minibatches at random from a replay buffer instead of training on each step as it comes?

Show the answer

Answer: a

Correlated updates make the network chase the recent past; replay spreads updates across many situations.

Check yourself

Why does taking the max over estimated Q-values overestimate?

Show the answer

Answer: a

E[max of noisy estimates] ≥ max of the true values. Double targets decouple choosing the action from scoring it.

Check yourself

How does a double Q target pick and score the next action?

Show the answer

Answer: a

The smaller of two critics is TD3's clipped double Q, a related fix for continuous actions.

Check yourself

Why does the dueling head subtract the mean advantage?

Show the answer

Answer: a

Centering the advantages gives V(s) a definite meaning: the average action's value.

Check yourself

When does a dueling head help most?

Show the answer

Answer: a

V(s) is learned from every transition in a state, whatever the action; the advantages only need to capture the differences.

11

Recap

Recap
  • DQN regresses Q(s, a) on r + γ·max Q_target(s′, ·), with the bootstrap dropped at terminal steps.
  • Replay breaks correlation; the target network holds targets still.
  • The max overestimates; double targets choose with one network and score with the other.
  • Dueling heads split Q into V plus mean-centered advantages.
  • The network's own value estimate isn't evidence; the exact value is.

Concepts in this lesson