Skip to content

Evaluating reinforcement learning honestly

Judge a learned policy by its own value, not its training curve. Use exact values when you can, compare methods at equal budgets over several seeds, report intervals, and never pick the best round with information you won't have.

Advanced ~15 min9 steps

What runs in CodeSplash

You will be able to

  • Explain why the training return is a poor measure of the learned policy
  • Read regret and the share of the optimal gain, including negative shares
  • Compare two algorithms at equal environment steps over several seeds, with intervals
  • Say when picking the best round is honest and when it leaks

Read first

01

The curve is not the policy

Read

A training returnTraining returnThe average discounted return of the episodes that finished in the last round, including exploratory actions. curve averages the episodes played while learning. Those episodes include exploration, a policy that changed mid-round, and the luck of a few episodes. It is a noisy view of a moving target.

The question you care about is different: how good is the policy you're keeping? In a small simulator, its exact valueExact policy valueThe policy's expected discounted return per episode, computed exactly from the environment's transition table. answers that with no noise at all. In a large one, run many fresh evaluation episodes with exploration off. With a real process and no simulator, it takes off-policy evaluation.

02

Regret and the share of the gain

Read

RegretPolicy regretHow much return per episode the learned policy gives up against the optimal one: optimal value minus its value. is the optimal value minus the policy's. The share of the optimal gainShare of the optimal gainHow far a policy gets from random actions (0) to the optimal policy (1); undefined when random actions are already optimal. puts it on a scale from random actions (0) to the optimum (1):

share=Vπ−VrandomV∗−Vrandom.\text{share} = \frac{V^\pi - V^{\text{random}}}{V^* - V^{\text{random}}} .

A negative share means the policy does worse than acting at random. That happens more often than learning curves suggest.

03

Two algorithms, one environment

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

A deep Q-network trained for 600 steps (40 episodes) in Custom formula earns 32.656 per episode against 52.691 for the optimal policy and 41.687 for random actions (regret 20.034, discount 0.9).

Learned policy value (exact)
32.656
Optimal policy value
52.691
Regret
20.034
Share of the optimal gain
−0.8207

Plots

Return per episode while trainingDoes the learned policy get closer to the best possible return as training goes on?
View data
CurveEnvironment stepsReturn per episode
Learned policy (exact)10026.700
Learned policy (exact)20026.700
Learned policy (exact)30026.700
Learned policy (exact)40026.700
Learned policy (exact)50026.700
Learned policy (exact)60032.656
Training episodes10038.651
Training episodes20037.898
Training episodes30028.298
Training episodes40027.406
Training episodes50028.714
Training episodes60026.459
Actions by state: learned vs optimalHow often does the learned policy choose each action, compared with the best policy?
View data
ActionShare of statesPolicy
wait0.6667Learned
push0.3333Learned
pull0Learned
wait0Optimal
push0.1111Optimal
pull0.8889Optimal

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (DQN)32.65620.034
Optimal policy52.6910
Random actions41.68711.004

Learned policy by state (9 states)

statesLearned actionOptimal actionQ(wait)Q(push)Q(pull)
s00waitpull8.0035.1281.978
s11waitpull11.9274.0424.325
s22pushpull6.45814.7075.745
s33pushpull8.16310.7043.684
s44pushpull12.29712.4893.435
s55waitpull15.06013.2035.848
s66waitpull15.11511.8195.149
s77waitpull11.3416.3881.812
s88waitpush12.7519.546−0.5352

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
11006138.65126.7003.5890.5166
2200130.472237.89826.7004.9570.3204
3300200.050028.29826.7006.3690.2040
4400260.050027.40626.7007.7450.1700
5500330.050028.71426.7009.2240.1253
6600400.050026.45932.65610.7040.1190
  • The learned policy gets only -82% of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.
  • 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; Custom formula (9 states, 3 actions, episodes of up to 15 steps, discount 0.9); 6 rounds × 100 steps, 20 updates of 64 replayed transitions per round (buffer 10000), hidden layers 32, learning rate 0.001, ε 1 → 0.05 over 30% of the rounds, double targets, 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 27bd262fde99fb09
# 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 "formula", discount 0.9: the app writes both into the environment files read below.
rounds <- as.integer(6)
steps <- as.integer(100)
updates <- as.integer(20)
batch_size <- as.integer(64)
buffer <- as.integer(10000)
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.05)
explore <- as.numeric(0.3)
double <- TRUE
dueling <- FALSE
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/formula-custom-settings/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/formula-custom-settings/out-r")

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

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

A deep Q-network trained for 600 steps (40 episodes) in Custom formula earns 32.656 per episode against 52.691 for the optimal policy and 41.687 for random actions (regret 20.034, discount 0.9).

Learned policy value (exact)
32.656
Optimal policy value
52.691
Regret
20.034
Share of the optimal gain
−0.8207

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

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (DQN)32.65620.034
Optimal policy52.6910
Random actions41.68711.004

Learned policy by state (9 states)

statesLearned actionOptimal actionQ(wait)Q(push)Q(pull)
s00waitpull8.0035.1281.978
s11waitpull11.9274.0424.325
s22pushpull6.45814.7075.745
s33pushpull8.16310.7043.684
s44pushpull12.29712.4893.435
s55waitpull15.06013.2035.848
s66waitpull15.11511.8195.149
s77waitpull11.3416.3881.812
s88waitpush12.7519.546−0.5352

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
11006138.65126.7003.5890.5166
2200130.472237.89826.7004.9570.3204
3300200.050028.29826.7006.3690.2040
4400260.050027.40626.7007.7450.1700
5500330.050028.71426.7009.2240.1253
6600400.050026.45932.65610.7040.1190
  • The learned policy gets only -82% of the way from random actions to the optimal policy: train for more rounds, explore longer or lower the learning rate.
  • 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; Custom formula (9 states, 3 actions, episodes of up to 15 steps, discount 0.9); 6 rounds × 100 steps, 20 updates of 64 replayed transitions per round (buffer 10000), hidden layers 32, learning rate 0.001, ε 1 → 0.05 over 30% of the rounds, double targets, 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 27bd262fde99fb09
# 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 "formula", discount 0.9: the app writes both into the environment files read below.
rounds = int(6)
steps = int(100)
updates = int(20)
batch_size = int(64)
buffer = int(10000)
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.05)
explore = float(0.3)
double = True
dueling = False
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/formula-custom-settings/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/formula-custom-settings/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,
})
Online policy learning (PPO)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

PPO trained for 500 steps (33 episodes) in Custom formula. Its most likely action in each state earns 52.626 per episode against 52.691 for the optimal policy and 41.687 for random actions (regret 0.065, discount 0.9); the stochastic policy itself earns 46.141.

Learned policy value (exact)
52.626
Optimal policy value
52.691
Regret
0.0648
Share of the optimal gain
0.9941

Plots

Return per episode while trainingDoes the learned policy get closer to the best possible return as training goes on?
View data
CurveEnvironment stepsReturn per episode
Learned policy (exact)10043.903
Learned policy (exact)20052.626
Learned policy (exact)30043.903
Learned policy (exact)40050.042
Learned policy (exact)50052.626
Training episodes10038.651
Training episodes20043.654
Training episodes30046.438
Training episodes40047.687
Training episodes50047.932
Actions by state: learned vs optimalHow often does the learned policy choose each action, compared with the best policy?
View data
ActionShare of statesPolicy
wait0Learned
push0.2222Learned
pull0.7778Learned
wait0Optimal
push0.1111Optimal
pull0.8889Optimal

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)52.6260.0648
Learned policy (sampled actions)46.1416.550
Optimal policy52.6910
Random actions41.68711.004

Learned policy by state (9 states)

statesLearned actionOptimal actionP(wait)P(push)P(pull)State value (network)
s00pullpull0.21380.39050.39586.932
s11pullpull0.19830.38070.421010.444
s22pullpull0.22450.37620.39937.425
s33pullpull0.20090.34000.459214.310
s44pullpull0.19930.32600.474815.643
s55pullpull0.16060.39600.443413.682
s66pullpull0.18200.38100.437014.009
s77pushpull0.17660.43990.383519.613
s88pushpush0.27740.37440.348214.851

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
1100638.65143.9031.4344.7381.095−0.00790.0%−0.0150
22001343.65452.6264.6425.4681.091−0.00033.0%−0.0219
33002046.43843.9037.7805.3321.081−0.01396.0%−0.0623
44002647.68750.04211.0765.2451.0690.00125.0%−0.1062
55003347.93252.62614.3104.2861.0670.00352.0%−0.0553
  • The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
  • Proximal policy optimization; Custom formula (9 states, 3 actions, episodes of up to 15 steps, discount 0.9); 5 iterations × 100 steps, 4 epochs per iteration in batches of 64, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; seed 42. Advantages are normalized over each rollout; 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 diagnostics compare the policy after each iteration's update with the one that collected the rollout.
The exact R script · R R version 4.5.1 (2025-06-13)
# Online policy learning with proximal policy optimization (PPO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_ppo 2.0.0 · spec 860409b6e1053de8
# 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 "formula", discount 0.9: the app writes both into the environment files read below.
rounds <- as.integer(5)
steps <- as.integer(100)
epochs <- as.integer(4)
batch_size <- 64
hidden <- as.integer(unlist(c(32)))
lr <- as.numeric(0.003)
encoding <- "one_hot" # one_hot | features
clip <- as.numeric(0.2)
gae_lambda <- as.numeric(0.95)
vf_coef <- as.numeric(0.5)
ent_coef <- as.numeric(0.01)
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-24905/decide.rl_ppo/formula-custom-settings/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-24905/decide.rl_ppo/formula-custom-settings/out-r")

# %% Train online
fit <- cs_rl_ppo(env, encoding, hidden, rounds, steps, epochs, batch_size, lr, clip, gae_lambda, vf_coef, ent_coef, seed)
trace <- fit$trace
policy <- fit$policy
sc <- cs_rl_scores(env, policy)
stochastic_value <- cs_rl_evaluate(env, fit$probs)
greedy_values <- vapply(trace, function(t) t$greedy_value, numeric(1))
best <- which.max(greedy_values)
last <- trace[[length(trace)]]
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 iteration or the number of iterations."
}
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 iterations or raise the entropy bonus.", 100 * sc$share)
}
if (last$approx_kl > 0.1) {
  warnings[[length(warnings) + 1L]] <- sprintf("The last update moved the policy a lot (approximate KL %.3f): lower the learning rate or the epochs per iteration.", last$approx_kl)
}
if (greedy_values[best] > sc$value + 1e-9 * max(1, abs(sc$value))) {
  warnings[[length(warnings) + 1L]] <- sprintf("An earlier iteration's policy (iteration %d) was better (%s) than the final one; 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("PPO trained for %s steps (%s episodes) in %s. Its most likely action in each state earns %s per episode against %s for the optimal policy and %s for random actions (regret %s, discount %s); the stochastic policy itself earns %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), fmt3(stochastic_value))
values <- list(policy_value = sc$value, stochastic_value = stochastic_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 = last$train_return, estimated_value = last$estimated_value,
               entropy = last$entropy, approx_kl = last$approx_kl, clip_fraction = last$clip_fraction,
               explained_variance = last$explained_variance, n_episodes = fit$episodes, env_steps = fit$env_steps, rounds_run = length(trace),
               final_loss = last$loss, n_states = S, n_actions = K, algorithm = "ppo")
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("P(%s)", actions[j]), type = "number")
pol_cols[[length(pol_cols) + 1L]] <- list(key = "value", label = "State value (network)", 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$probs[live, j])
pol_df$value <- as.numeric(fit$values[live])
eval_df <- data.frame(policy = c("Learned policy (most likely action)", "Learned policy (sampled actions)", "Optimal policy", "Random actions"),
                      value = c(sc$value, stochastic_value, opt_value, uni_value),
                      regret = c(sc$regret, opt_value - stochastic_value, 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)),
                       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)),
                       entropy = vapply(trace, function(t) as.numeric(t$entropy), numeric(1)),
                       approx_kl = vapply(trace, function(t) as.numeric(t$approx_kl), numeric(1)),
                       clip_fraction = vapply(trace, function(t) as.numeric(t$clip_fraction), numeric(1)),
                       explained_variance = vapply(trace, function(t) num_or_na(t$explained_variance), 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_ppo",
  methodVersion = "2.0.0",
  title = "Online policy learning (PPO)",
  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 iteration",
         columns = list(list(key = "round", label = "Iteration", type = "integer"), list(key = "env_steps", label = "Environment steps", type = "integer"),
                        list(key = "episodes", label = "Episodes", type = "integer"), 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"),
                        list(key = "entropy", label = "Entropy", type = "number"), list(key = "approx_kl", label = "Approximate KL", type = "number"),
                        list(key = "clip_fraction", label = "Clipped share", type = "percent"),
                        list(key = "explained_variance", label = "Explained variance", type = "number")),
         rows = train_df)
  ),
  warnings = warnings,
  notes = list(paste0(
    sprintf("Proximal policy optimization; %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 iterations × %d steps, %d epochs per iteration in batches of %s, hidden layers %s, learning rate %s, clip range %s, λ %s, value weight %s, entropy bonus %s; seed %s. ",
            rounds, steps, epochs, if (is.null(batch_size)) "the whole rollout" else as.character(batch_size), paste(hidden, collapse = ", "),
            format(lr, digits = 15), format(clip, digits = 15), format(gae_lambda, digits = 15), format(vf_coef, digits = 15),
            format(ent_coef, digits = 15), seed),
    "Advantages are normalized over each rollout; 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 diagnostics compare the policy ",
    "after each iteration's update with the one that collected the rollout."
  )),
  values = values,
  charts = charts
))
Python

PPO trained for 500 steps (33 episodes) in Custom formula. Its most likely action in each state earns 52.626 per episode against 52.691 for the optimal policy and 41.687 for random actions (regret 0.065, discount 0.9); the stochastic policy itself earns 46.141.

Learned policy value (exact)
52.626
Optimal policy value
52.691
Regret
0.0648
Share of the optimal gain
0.9941

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

Exact return per episode

PolicyReturn per episodeRegret
Learned policy (most likely action)52.6260.0648
Learned policy (sampled actions)46.1416.550
Optimal policy52.6910
Random actions41.68711.004

Learned policy by state (9 states)

statesLearned actionOptimal actionP(wait)P(push)P(pull)State value (network)
s00pullpull0.21380.39050.39586.932
s11pullpull0.19830.38070.421010.444
s22pullpull0.22450.37620.39937.425
s33pullpull0.20090.34000.459214.310
s44pullpull0.19930.32600.474815.643
s55pullpull0.16060.39600.443413.682
s66pullpull0.18200.38100.437014.009
s77pushpull0.17660.43990.383519.613
s88pushpush0.27740.37440.348214.851

Training by iteration

IterationEnvironment stepsEpisodesTraining returnLearned policy value (exact)Network's start valueLossEntropyApproximate KLClipped shareExplained variance
1100638.65143.9031.4344.7381.095−0.00790.0%−0.0150
22001343.65452.6264.6425.4681.091−0.00033.0%−0.0219
33002046.43843.9037.7805.3321.081−0.01396.0%−0.0623
44002647.68750.04211.0765.2451.0690.00125.0%−0.1062
55003347.93252.62614.3104.2861.0670.00352.0%−0.0553
  • The environment is simulated: a policy that does well here does well in the real process only as far as the environment describes it.
  • Proximal policy optimization; Custom formula (9 states, 3 actions, episodes of up to 15 steps, discount 0.9); 5 iterations × 100 steps, 4 epochs per iteration in batches of 64, hidden layers 32, learning rate 0.003, clip range 0.2, λ 0.95, value weight 0.5, entropy bonus 0.01; seed 42. Advantages are normalized over each rollout; 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 diagnostics compare the policy after each iteration's update with the one that collected the rollout.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Online policy learning with proximal policy optimization (PPO)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.rl_ppo 2.0.0 · spec 860409b6e1053de8
# 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 "formula", discount 0.9: the app writes both into the environment files read below.
rounds = int(5)
steps = int(100)
epochs = int(4)
batch_size = 64
hidden = [int(u) for u in [32]]
lr = float(0.003)
encoding = "one_hot"  # one_hot | features
clip = float(0.2)
gae_lambda = float(0.95)
vf_coef = float(0.5)
ent_coef = float(0.01)
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-24905/decide.rl_ppo/formula-custom-settings/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-24905/decide.rl_ppo/formula-custom-settings/out-python",
)

# %% Train online
fit = rl.ppo(env, encoding, hidden, rounds, steps, epochs, batch_size, lr, clip, gae_lambda, vf_coef, ent_coef, seed)
trace = fit["trace"]
policy = fit["policy"]
sc = rl.scores(env, policy)
stochastic_value = rl.evaluate(env, fit["probs"])
best = max(range(len(trace)), key=lambda i: (trace[i]["greedy_value"], -i))
last = trace[-1]
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 iteration or the number of iterations.")
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 iterations or raise the entropy bonus.")
if last["approx_kl"] > 0.1:
    warnings.append(f"The last update moved the policy a lot (approximate KL {last['approx_kl']:.3f}): lower the learning rate or the epochs per iteration.")
if trace[best]["greedy_value"] > sc["value"] + 1e-9 * max(1.0, abs(sc["value"])):
    warnings.append(f"An earlier iteration's policy (iteration {trace[best]['round']}) was better ({trace[best]['greedy_value']:.4g}) than the final one; 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"]
live = [s for s in range(S) if not env["terminal"][s]]
optimal = meta["optimal_policy"]
summary = (
    f"PPO trained for {fit['env_steps']:,} steps ({fit['episodes']:,} episodes) in {meta['title']}. Its most likely action in each state earns "
    f"{sc['value']:.3f} per episode against {opt_value:.3f} for the optimal policy and {uni_value:.3f} for random actions (regret "
    f"{sc['regret']:.3f}, discount {gamma:g}); the stochastic policy itself earns {stochastic_value:.3f}."
)
values = {
    "policy_value": sc["value"], "stochastic_value": stochastic_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": last["train_return"], "estimated_value": last["estimated_value"],
    "entropy": last["entropy"], "approx_kl": last["approx_kl"], "clip_fraction": last["clip_fraction"],
    "explained_variance": last["explained_variance"], "n_episodes": fit["episodes"], "env_steps": fit["env_steps"], "rounds_run": len(trace),
    "final_loss": last["loss"], "n_states": S, "n_actions": K, "algorithm": "ppo",
}
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"P({a})", "type": "number"} for j, a in enumerate(actions)]
pol_cols.append({"key": "value", "label": "State value (network)", "type": "number"})
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["probs"][s, j]) for j in range(K)})
    r["value"] = float(fit["values"][s])
    pol_rows.append(r)
eval_rows = [
    {"policy": "Learned policy (most likely action)", "value": sc["value"], "regret": sc["regret"]},
    {"policy": "Learned policy (sampled actions)", "value": stochastic_value, "regret": opt_value - stochastic_value},
    {"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_ppo",
    "methodVersion": "2.0.0",
    "title": "Online policy learning (PPO)",
    "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 iteration",
         "columns": [{"key": "round", "label": "Iteration", "type": "integer"}, {"key": "env_steps", "label": "Environment steps", "type": "integer"},
                     {"key": "episodes", "label": "Episodes", "type": "integer"}, {"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"},
                     {"key": "entropy", "label": "Entropy", "type": "number"}, {"key": "approx_kl", "label": "Approximate KL", "type": "number"},
                     {"key": "clip_fraction", "label": "Clipped share", "type": "percent"},
                     {"key": "explained_variance", "label": "Explained variance", "type": "number"}],
         "rows": trace},
    ],
    "warnings": warnings,
    "notes": [
        f"Proximal policy optimization; {meta['title']} ({S} states, {K} actions, episodes of up to {env['horizon']} steps, discount {gamma:g}); "
        f"{rounds} iterations × {steps} steps, {epochs} epochs per iteration in batches of {batch_size if batch_size is not None else 'the whole rollout'}, "
        f"hidden layers {', '.join(str(h) for h in hidden)}, learning rate {lr:g}, clip range {clip:g}, λ {gae_lambda:g}, value weight {vf_coef:g}, "
        f"entropy bonus {ent_coef:g}; seed {seed}. Advantages are normalized over each rollout; 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 "
        "diagnostics compare the policy after each iteration's update with the one that collected the rollout.",
    ],
    "values": values,
    "charts": charts,
})

On the same custom environment, DQN's final policy gets a share of −82.1%: worse than random. PPO's gets 99.4%. DQN ran 600 environment steps and PPO 500, one seed each.

Does that make PPO the better algorithm? Not from this. One seed, unequal budgets, default settings for both: it's an anecdote.

04

A fair comparison

Read
  • Equal budgets: the same number of environment steps (and similar tuning effort) for each method.
  • Several seeds: deep RL varies a lot from seed to seed; report every run, not the best.
  • Robust summaries: the interquartile meanInterquartile mean (IQM)The mean of the middle half of the runs: steadier than the mean across a few seeds, less wasteful than the median. of the runs, with a bootstrap interval; the median wastes data and the mean is swayed by one wild run.
  • The same evaluation for all: exact values here, or many fresh episodes with exploration off.
05

Picking the best round

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

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

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

Plots

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

Exact return per episode

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

Learned policy by state (7 states)

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

Training by round

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

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

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

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

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

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

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

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

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

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

Exact return per episode

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

Learned policy by state (7 states)

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

Training by round

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

# %% Setup
import numpy as np

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

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

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

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

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

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

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

This run's best policy came in round 1, worth 1.435; the final one is worth 0.184. CodeSplash reports both and keeps the final policy.

Choosing the best round by its exact value works only because this environment can be solved. With a real process you'd choose by noisy evaluation episodes, and the chosen round's score would be optimistic, the same winner's curse as picking the best of many models on one test set. Choose on one set of evaluation episodes; report on fresh ones.

06

What runs here

Read
07

Common mistakes

Read
08

Check: evaluating RL

Checkpoint

Check yourself

A DQN policy's share of the optimal gain is −20%. What does that mean?

Show the answer

Answer: a

The share is 0 for random actions and 1 for the optimum, so a negative share is below random.

Check yourself

Random actions earn 10 per episode, the optimum 30, and the learned policy 22. What is the share of the optimal gain?

Show the answer

Answer: 0.6

(22 − 10) / (30 − 10) = 12 / 20 = 0.6.

Check yourself

Which comparison of DQN and PPO on a new task is fair?

Show the answer

Answer: a

Equal budgets, several seeds, robust summaries with intervals and a shared evaluation keep the comparison from being an anecdote.

Check yourself

Why is the last round's training return often below the learned policy's exact value?

Show the answer

Answer: a

The exact value comes from the transition table, with no noise and no exploration.

Check yourself

With a real process and no exact values, you pick the training round whose evaluation episodes scored best. What is wrong with reporting that score?

Show the answer

Answer: a

Selecting the maximum of noisy scores biases that maximum upward, the winner's curse.

09

Recap

Recap
  • Judge the policy you keep by its own value, not the training curve.
  • Regret and the share of the optimal gain need a random baseline and the optimum; negative shares mean worse than random.
  • Compare algorithms at equal budgets over several seeds, with interquartile means and intervals.
  • Picking the best round is honest only with exact values; otherwise select on some episodes and report on fresh ones.

Concepts in this lesson