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.
What runs in CodeSplash
- DRL001Deep Q-network (DQN) Runs in CodeSplash (Experimental)
- DRL002Double DQN Runs in CodeSplash
- DRL003Dueling DQN architecture Runs in CodeSplash
- Online policy learning with a deep Q-network (DQN) Experimental
- Offline policy learning from logged episodes Verified in Python and R
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
Q-learning with a network
ReadA 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 for every action from the state. It trains toward the Bellman target:
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.
Trips from the start until the goal, the pit or 100 steps.
How much a reward one step later is worth now.
Step size of every update.
Q-learning only: share of steps that take a random action.
PPO only: how far the policy may move from the one that collected the batch.
Chance that a move turns 90° to either side.
Working…
Two stabilizers
ReadTraining 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 , updated every so often. Both are on in CodeSplash's decide.rl_dqn.
The max is optimistic
ReadThe 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:
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.
Dueling heads
ReadIn 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 and per-action advantages :
Subtracting the mean pins down the split: otherwise any constant could move between and . 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.
Exploring while learning
ExploreEExplorable · 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?
Commit your prediction above to see the result
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.
Run it: the network's opinion of itself
In the appA 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
View data
| Curve | Environment steps | Return per episode |
|---|---|---|
| Learned policy (exact) | 120 | 1.435 |
| Learned policy (exact) | 240 | 1.435 |
| Learned policy (exact) | 360 | 1.435 |
| Learned policy (exact) | 480 | 0.6682 |
| Learned policy (exact) | 600 | 0.1840 |
| Learned policy (exact) | 720 | 0.1840 |
| Training episodes | 120 | 1.467 |
| Training episodes | 240 | 1.925 |
| Training episodes | 360 | 1.090 |
| Training episodes | 480 | 3.135 |
| Training episodes | 600 | −1.305 |
| Training episodes | 720 | 3.426 |
View data
| Action | Share of states | Policy |
|---|---|---|
| accept | 0.7143 | Learned |
| reject | 0.2857 | Learned |
| accept | 0.2857 | Optimal |
| reject | 0.7143 | Optimal |
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (DQN) | 0.1840 | 3.085 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | Q(accept) | Q(reject) |
|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 1.647 | 1.248 |
| queue 1 | 1 | accept | reject | 1.002 | 0.5705 |
| queue 2 | 2 | accept | reject | 0.0186 | −0.2539 |
| queue 3 | 3 | accept | reject | −0.2849 | −1.078 |
| queue 4 | 4 | accept | reject | 0.3836 | −0.5381 |
| queue 5 | 5 | reject | reject | 0.1521 | 0.5791 |
| queue 6 | 6 | reject | accept | −0.3189 | 0.0582 |
Training by round
| Round | Environment steps | Episodes | Exploration (ε) | Training return | Learned policy value (exact) | Network's start value | Loss |
|---|---|---|---|---|---|---|---|
| 1 | 120 | 4 | 1 | 1.467 | 1.435 | 1.088 | 0.0299 |
| 2 | 240 | 8 | 0.7000 | 1.925 | 1.435 | 1.131 | 0.0277 |
| 3 | 360 | 12 | 0.4000 | 1.090 | 1.435 | 1.353 | 0.0194 |
| 4 | 480 | 16 | 0.1000 | 3.135 | 0.6682 | 1.423 | 0.0174 |
| 5 | 600 | 20 | 0.1000 | −1.305 | 0.1840 | 1.596 | 0.0433 |
| 6 | 720 | 24 | 0.1000 | 3.426 | 0.1840 | 1.647 | 0.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
))
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
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (DQN) | 0.1840 | 3.085 |
| Optimal policy | 3.269 | 0 |
| Random actions | 1.651 | 1.618 |
Learned policy by state (7 states)
| state | queue | Learned action | Optimal action | Q(accept) | Q(reject) |
|---|---|---|---|---|---|
| queue 0 | 0 | accept | accept | 1.647 | 1.248 |
| queue 1 | 1 | accept | reject | 1.002 | 0.5705 |
| queue 2 | 2 | accept | reject | 0.0186 | −0.2539 |
| queue 3 | 3 | accept | reject | −0.2849 | −1.078 |
| queue 4 | 4 | accept | reject | 0.3836 | −0.5381 |
| queue 5 | 5 | reject | reject | 0.1521 | 0.5791 |
| queue 6 | 6 | reject | accept | −0.3189 | 0.0582 |
Training by round
| Round | Environment steps | Episodes | Exploration (ε) | Training return | Learned policy value (exact) | Network's start value | Loss |
|---|---|---|---|---|---|---|---|
| 1 | 120 | 4 | 1 | 1.467 | 1.435 | 1.088 | 0.0299 |
| 2 | 240 | 8 | 0.7000 | 1.925 | 1.435 | 1.131 | 0.0277 |
| 3 | 360 | 12 | 0.4000 | 1.090 | 1.435 | 1.353 | 0.0194 |
| 4 | 480 | 16 | 0.1000 | 3.135 | 0.6682 | 1.423 | 0.0174 |
| 5 | 600 | 20 | 0.1000 | −1.305 | 0.1840 | 1.596 | 0.0433 |
| 6 | 720 | 24 | 0.1000 | 3.426 | 0.1840 | 1.647 | 0.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.
Run it: features and squared error
In the appA 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
View data
| Curve | Environment steps | Return per episode |
|---|---|---|
| Learned policy (exact) | 120 | 28.944 |
| Learned policy (exact) | 240 | 28.944 |
| Learned policy (exact) | 360 | 30.185 |
| Learned policy (exact) | 480 | 31.113 |
| Learned policy (exact) | 600 | 25.659 |
| Learned policy (exact) | 720 | 29.265 |
| Training episodes | 120 | 24.739 |
| Training episodes | 240 | 27.563 |
| Training episodes | 360 | 26.023 |
| Training episodes | 480 | 27.308 |
| Training episodes | 600 | 25.559 |
| Training episodes | 720 | 24.981 |
View data
| Action | Share of states | Policy |
|---|---|---|
| order 0 | 0.3333 | Learned |
| order 2 | 0.3333 | Learned |
| order 4 | 0.3333 | Learned |
| order 0 | 0.5556 | Optimal |
| order 2 | 0.2222 | Optimal |
| order 4 | 0.2222 | Optimal |
Exact return per episode
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (DQN) | 29.265 | 1.848 |
| Optimal policy | 31.113 | 0 |
| Random actions | 24.166 | 6.947 |
Learned policy by state (9 states)
| state | stock | Learned action | Optimal action | Q(order 0) | Q(order 2) | Q(order 4) |
|---|---|---|---|---|---|---|
| stock 0 | 0 | order 4 | order 4 | 6.849 | 9.335 | 10.459 |
| stock 1 | 1 | order 4 | order 4 | 9.197 | 10.861 | 11.356 |
| stock 2 | 2 | order 4 | order 2 | 10.746 | 12.112 | 12.298 |
| stock 3 | 3 | order 2 | order 2 | 12.296 | 13.364 | 13.240 |
| stock 4 | 4 | order 2 | order 0 | 13.632 | 14.345 | 14.159 |
| stock 5 | 5 | order 2 | order 0 | 14.892 | 15.230 | 15.068 |
| stock 6 | 6 | order 0 | order 0 | 16.152 | 16.114 | 15.978 |
| stock 7 | 7 | order 0 | order 0 | 17.412 | 16.999 | 16.888 |
| stock 8 | 8 | order 0 | order 0 | 18.672 | 17.884 | 17.797 |
Training by round
| Round | Environment steps | Episodes | Exploration (ε) | Training return | Learned policy value (exact) | Network's start value | Loss |
|---|---|---|---|---|---|---|---|
| 1 | 120 | 10 | 1 | 24.739 | 28.944 | 5.767 | 0.0114 |
| 2 | 240 | 20 | 0.4722 | 27.563 | 28.944 | 5.126 | 0.0063 |
| 3 | 360 | 30 | 0.0500 | 26.023 | 30.185 | 9.720 | 0.0068 |
| 4 | 480 | 40 | 0.0500 | 27.308 | 31.113 | 9.364 | 0.0064 |
| 5 | 600 | 50 | 0.0500 | 25.559 | 25.659 | 13.116 | 0.0082 |
| 6 | 720 | 60 | 0.0500 | 24.981 | 29.265 | 12.298 | 0.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
))
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
| Policy | Return per episode | Regret |
|---|---|---|
| Learned policy (DQN) | 29.265 | 1.848 |
| Optimal policy | 31.113 | 0 |
| Random actions | 24.166 | 6.947 |
Learned policy by state (9 states)
| state | stock | Learned action | Optimal action | Q(order 0) | Q(order 2) | Q(order 4) |
|---|---|---|---|---|---|---|
| stock 0 | 0 | order 4 | order 4 | 6.849 | 9.335 | 10.459 |
| stock 1 | 1 | order 4 | order 4 | 9.197 | 10.861 | 11.356 |
| stock 2 | 2 | order 4 | order 2 | 10.746 | 12.112 | 12.298 |
| stock 3 | 3 | order 2 | order 2 | 12.296 | 13.364 | 13.240 |
| stock 4 | 4 | order 2 | order 0 | 13.632 | 14.345 | 14.159 |
| stock 5 | 5 | order 2 | order 0 | 14.892 | 15.230 | 15.068 |
| stock 6 | 6 | order 0 | order 0 | 16.152 | 16.114 | 15.978 |
| stock 7 | 7 | order 0 | order 0 | 17.412 | 16.999 | 16.888 |
| stock 8 | 8 | order 0 | order 0 | 18.672 | 17.884 | 17.797 |
Training by round
| Round | Environment steps | Episodes | Exploration (ε) | Training return | Learned policy value (exact) | Network's start value | Loss |
|---|---|---|---|---|---|---|---|
| 1 | 120 | 10 | 1 | 24.739 | 28.944 | 5.767 | 0.0114 |
| 2 | 240 | 20 | 0.4722 | 27.563 | 28.944 | 5.126 | 0.0063 |
| 3 | 360 | 30 | 0.0500 | 26.023 | 30.185 | 9.720 | 0.0068 |
| 4 | 480 | 40 | 0.0500 | 27.308 | 31.113 | 9.364 | 0.0064 |
| 5 | 600 | 50 | 0.0500 | 25.559 | 25.659 | 13.116 | 0.0082 |
| 6 | 720 | 60 | 0.0500 | 24.981 | 29.265 | 12.298 | 0.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:
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
View data
| Value | Upper | Policy and estimator | Lower |
|---|---|---|---|
| 0.2946 | 0.3409 | Conservative Q-learning · Fitted Q evaluation | 0.2554 |
| 0.5120 | 0.5317 | Behavior cloning (baseline) · Fitted Q evaluation | 0.4939 |
| 0.0487 | 0.1387 | Logged policy · Observed return | −0.0376 |
View data
| Iteration | Estimated value |
|---|---|
| 1 | 0.7110 |
| 2 | 0.7527 |
| 3 | 0.6095 |
View data
| Action | Share | Policy |
|---|---|---|
| left | 0.1688 | Logged |
| stay | 0.1906 | Logged |
| right | 0.6406 | Logged |
| left | 0.2000 | Learned |
| stay | 0 | Learned |
| right | 0.8000 | Learned |
Estimated return per episode
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Conservative Q-learning | Fitted Q evaluation | 0.2946 | 0.2554 | 0.3409 |
| Behavior cloning (baseline) | Fitted Q evaluation | 0.5120 | 0.4939 | 0.5317 |
| Logged policy | Observed return | 0.0487 | −0.0376 | 0.1387 |
Learned policy by state (12 of 12 distinct states)
| position | weather today | Learned action | Q(left) | Q(stay) | Q(right) |
|---|---|---|---|---|---|
| 1 | sun | right | 0.2828 | 0.1079 | 0.4264 |
| 2 | sun | right | 0.1012 | 0.1971 | 0.6267 |
| 3 | rain | right | 0.3141 | 0.2717 | 0.6001 |
| 4 | rain | right | 0.4233 | 0.5839 | 0.9480 |
| 5 | rain | right | 0.5493 | 0.8991 | 1.274 |
| 1 | rain | left | 0.7388 | 0.2424 | 0.6814 |
| 0 | sun | right | 0.0616 | 0.4905 | 0.5717 |
| 3 | sun | right | 0.0939 | 0.4640 | 0.9343 |
| 2 | rain | left | 0.4757 | 0.0416 | 0.4155 |
| 4 | sun | right | 0.0874 | 0.7541 | 1.220 |
| 5 | sun | right | 0.0794 | 1.027 | 1.509 |
| 0 | rain | left | 0.9531 | 0.6782 | 0.8639 |
Actions: logged vs learned policy
| action | Logged share | Learned share |
|---|---|---|
| left | 16.9% | 20.0% |
| stay | 19.1% | 0.0% |
| right | 64.1% | 80.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 0.6742 | 0.7110 |
| 2 | 0.6012 | 0.7527 |
| 3 | 0.5447 | 0.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
))
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
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Conservative Q-learning | Fitted Q evaluation | 0.2946 | 0.2554 | 0.3409 |
| Behavior cloning (baseline) | Fitted Q evaluation | 0.5120 | 0.4939 | 0.5317 |
| Logged policy | Observed return | 0.0487 | −0.0376 | 0.1387 |
Learned policy by state (12 of 12 distinct states)
| position | weather today | Learned action | Q(left) | Q(stay) | Q(right) |
|---|---|---|---|---|---|
| 1 | sun | right | 0.2828 | 0.1079 | 0.4264 |
| 2 | sun | right | 0.1012 | 0.1971 | 0.6267 |
| 3 | rain | right | 0.3141 | 0.2717 | 0.6001 |
| 4 | rain | right | 0.4233 | 0.5839 | 0.9480 |
| 5 | rain | right | 0.5493 | 0.8991 | 1.274 |
| 1 | rain | left | 0.7388 | 0.2424 | 0.6814 |
| 0 | sun | right | 0.0616 | 0.4905 | 0.5717 |
| 3 | sun | right | 0.0939 | 0.4640 | 0.9343 |
| 2 | rain | left | 0.4757 | 0.0416 | 0.4155 |
| 4 | sun | right | 0.0874 | 0.7541 | 1.220 |
| 5 | sun | right | 0.0794 | 1.027 | 1.509 |
| 0 | rain | left | 0.9531 | 0.6782 | 0.8639 |
Actions: logged vs learned policy
| action | Logged share | Learned share |
|---|---|---|
| left | 16.9% | 20.0% |
| stay | 19.1% | 0.0% |
| right | 64.1% | 80.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 0.6742 | 0.7110 |
| 2 | 0.6012 | 0.7527 |
| 3 | 0.5447 | 0.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,
})
What runs here
ReadCommon mistakes
ReadCheck: DQN and its fixes
CheckpointCheck 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.
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