Skip to content

MDPs, values and the Bellman equation

Write a sequential decision problem as a Markov decision process, define the value of a state and of an action, and solve a small one exactly with the Bellman equation - the yardstick every learned policy in this track is measured against.

Applied ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Name the parts of a Markov decision process and the Markov assumption
  • Define V(s) and Q(s, a) and the discounted return they average
  • Apply one Bellman optimality backup by hand
  • Explain why a small MDP's optimal value is a fair yardstick for learned policies

Read first

01

Decisions that shape the next decision

Read

Reinforcement learningReinforcement learningLearning to act from states, actions and rewards. The data depend on the policy, so the usual train–test logic changes. chooses actions whose effects carry forward. A Markov decision processMarkov decision process (MDP)States, actions, transition probabilities and rewards, where what happens next depends only on the current state and action. writes such a problem down:

  • states ss and actions aa;
  • transition probabilities P(s′∣s,a)P(s' \mid s, a);
  • rewards r(s,a,s′)r(s, a, s');
  • a discount γ\gamma between 0 and 1.

The Markov assumption says the next state depends only on the current state and action. If the past matters, put what matters into the state.

02

Returns and values

Read

A policy π\pi picks actions. Its discounted returnDiscounted returnAn episode's rewards added up with later ones counted less: r₁ + γr₂ + γ²r₃ … for a discount γ between 0 and 1. from time tt is Gt=rt+γrt+1+γ2rt+2+…G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + \dots

The value functionsValue function (V and Q)V(s): the expected discounted return from state s under a policy. Q(s, a): the same after first taking action a. average that return:

Vπ(s)=Eπ[Gt∣st=s],Qπ(s,a)=Eπ[Gt∣st=s,at=a].V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s], \qquad Q^\pi(s, a) = \mathbb{E}_\pi[G_t \mid s_t = s, a_t = a].

VV scores a state under the policy; QQ scores taking action aa first and following the policy after. Every method in this track estimates one of them, the policy itself, or both.

03

Fix a policy, get a Markov chain

Explore

AExplorable · A Markov chain playground

When tomorrow depends only on today, where does a process settle in the long run?

In the long run, what share of time does the chain spend in A?

0.50
How sure?
0.80
0.60
500
long-run 0.67

The strip shows the first steps: state A in one color, B in the other. Long runs of one color mean a sticky chain.

Commit your prediction above to see the result

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

Make your prediction to see the result.

Once a policy fixes the action in every state, an MDP's states follow a Markov chain: each row of the transition matrix is where that state's chosen action leads. Change a transition and watch where the chain spends its time. Changing the policy changes the chain, and so the rewards it collects.

04

The Bellman equation

Read

Values satisfy a one-step consistency, the Bellman equationBellman equationA value equals the immediate reward plus the discounted value of where you land; the optimal one takes the best action.. For the best possible policy:

Q∗(s,a)=E[ r+γmax⁡a′Q∗(s′,a′) ],V∗(s)=max⁡aQ∗(s,a).Q^*(s, a) = \mathbb{E}\big[\, r + \gamma \max_{a'} Q^*(s', a') \,\big], \qquad V^*(s) = \max_a Q^*(s, a).

When the transition table is known and small, value iterationValue iterationSolve a known MDP by applying the Bellman optimality backup to every state until the values stop changing. applies this backup to every state again and again until nothing changes. The result is exact: the optimal policy and its value.

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

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

Learner

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

500

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

0.95

How much a reward one step later is worth now.

0.50

Step size of every update.

0.10

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

0.20

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

0.10

Chance that a move turns 90° to either side.

Simulating…
Working…

Working…

05

A yardstick that doesn't move

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 4,000 steps (133 episodes) in Admission control earns 3.269 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 0.000, discount 0.95).

Learned policy value (exact)
3.269
Optimal policy value
3.269
Regret
0
Share of the optimal gain
1

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)200−0.0916
Learned policy (exact)400−0.0916
Learned policy (exact)600−0.0916
Learned policy (exact)800−0.0916
Learned policy (exact)1,000−0.0916
Learned policy (exact)1,200−0.0916
Learned policy (exact)1,400−0.0916
Learned policy (exact)1,600−0.0916
Learned policy (exact)1,800−0.0916
Learned policy (exact)2,000−0.0916
Learned policy (exact)2,200−0.0916
Learned policy (exact)2,400−0.0916
Learned policy (exact)2,6002.447
Learned policy (exact)2,8003.269
Learned policy (exact)3,0003.269
Learned policy (exact)3,2003.269
Learned policy (exact)3,4003.269
Learned policy (exact)3,6003.269
Learned policy (exact)3,8003.269
Learned policy (exact)4,0003.269
Training episodes2001.222
Training episodes4002.113
Training episodes6001.749
Training episodes8002.077
Training episodes1,000−1.104
Training episodes1,2001.474
Training episodes1,4003.192
Training episodes1,6000.2773
Training episodes1,8000.5929
Training episodes2,0001.501
Training episodes2,2000.2483
Training episodes2,4000.8008
Training episodes2,6000.3695
Training episodes2,8002.736
Training episodes3,0002.776
Training episodes3,2003.126
Training episodes3,4003.334
Training episodes3,6003.417
Training episodes3,8002.962
Training episodes4,0003.278
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.1429Learned
reject0.8571Learned
accept0.2857Optimal
reject0.7143Optimal

Exact return per episode

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

Learned policy by state (7 states)

statequeueLearned actionOptimal actionQ(accept)Q(reject)
queue 00acceptaccept2.3712.162
queue 11rejectreject1.2811.464
queue 22rejectreject−0.18230.0542
queue 33rejectreject−1.760−1.693
queue 44rejectreject−3.285−3.076
queue 55rejectreject−4.543−4.428
queue 66rejectaccept−5.200−5.118

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
1200611.222−0.09160.94540.0263
2400130.84172.113−0.09161.0230.0173
3600200.68331.749−0.09161.2640.0166
4800260.52502.077−0.09161.3370.0191
51,000330.3667−1.104−0.09161.5570.0254
61,200400.20831.474−0.09161.5820.0244
71,400460.05003.192−0.09161.7720.0273
81,600530.05000.2773−0.09161.7440.0253
91,800600.05000.5929−0.09161.8930.0296
102,000660.05001.501−0.09161.9150.0270
112,200730.05000.2483−0.09162.0030.0306
122,400800.05000.8008−0.09162.0480.0318
132,600860.05000.36952.4472.1140.0362
142,800930.05002.7363.2692.1710.0416
153,0001000.05002.7763.2692.1790.0441
163,2001060.05003.1263.2692.2440.0495
173,4001130.05003.3343.2692.2390.0488
183,6001200.05003.4173.2692.2690.0547
193,8001260.05002.9623.2692.3360.0535
204,0001330.05003.2783.2692.3710.0600
  • 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); 20 rounds × 200 steps, 50 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 ced53f94fa51c811
# 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(20)
steps <- as.integer(200)
updates <- as.integer(50)
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/queue-worked-example/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-worked-example/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 4,000 steps (133 episodes) in Admission control earns 3.269 per episode against 3.269 for the optimal policy and 1.651 for random actions (regret 0.000, discount 0.95).

Learned policy value (exact)
3.269
Optimal policy value
3.269
Regret
0
Share of the optimal gain
1

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

Exact return per episode

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

Learned policy by state (7 states)

statequeueLearned actionOptimal actionQ(accept)Q(reject)
queue 00acceptaccept2.3712.162
queue 11rejectreject1.2811.464
queue 22rejectreject−0.18230.0542
queue 33rejectreject−1.760−1.693
queue 44rejectreject−3.285−3.076
queue 55rejectreject−4.543−4.428
queue 66rejectaccept−5.200−5.118

Training by round

RoundEnvironment stepsEpisodesExploration (ε)Training returnLearned policy value (exact)Network's start valueLoss
1200611.222−0.09160.94540.0263
2400130.84172.113−0.09161.0230.0173
3600200.68331.749−0.09161.2640.0166
4800260.52502.077−0.09161.3370.0191
51,000330.3667−1.104−0.09161.5570.0254
61,200400.20831.474−0.09161.5820.0244
71,400460.05003.192−0.09161.7720.0273
81,600530.05000.2773−0.09161.7440.0253
91,800600.05000.5929−0.09161.8930.0296
102,000660.05001.501−0.09161.9150.0270
112,200730.05000.2483−0.09162.0030.0306
122,400800.05000.8008−0.09162.0480.0318
132,600860.05000.36952.4472.1140.0362
142,800930.05002.7363.2692.1710.0416
153,0001000.05002.7763.2692.1790.0441
163,2001060.05003.1263.2692.2440.0495
173,4001130.05003.3343.2692.2390.0488
183,6001200.05003.4173.2692.2690.0547
193,8001260.05002.9623.2692.3360.0535
204,0001330.05003.2783.2692.3710.0600
  • 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); 20 rounds × 200 steps, 50 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 ced53f94fa51c811
# 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(20)
steps = int(200)
updates = int(50)
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/queue-worked-example/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-worked-example/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,
})

The Policy learning studio's environments are small MDPs: this admission-control queue has 7 states and 2 actions. CodeSplash solves each one exactly, so every learned policy gets three numbers with no simulation noise: the best possible value, 3.269; random actions, 1.651; and the learned policy's own exact value, here 3.269.

Large problems, where deep RL earns its keep, have no such yardstick. That's why this track practices on small ones.

06

Predict: a lower discount

Predict

Predict first

You lower the discount per step from 0.99 to 0.9. How does the optimal policy's outlook change?

It plans further aheadIt cares more about the next few stepsThe policy can't change
Reveal

It cares more about the next few steps. A reward k steps away counts γᵏ; with γ = 0.9 a reward 20 steps out counts about an eighth, against about four fifths with 0.99. The optimal policy can change as a result.

07

Common mistakes

Read
08

Check: MDPs and values

Checkpoint

Check yourself

From state s, action a earns reward 1 and always leads to state s′, where the best action is worth Q* = 2. With γ = 0.9, what is Q*(s, a)?

Show the answer

Answer: 2.8

Q*(s, a) = 1 + 0.9 × 2 = 2.8. With several possible next states you'd average over them, weighted by their probabilities.

Check yourself

In an inventory problem, tomorrow's demand depends on whether a promotion ran in each of the last three days, but the state holds only today's stock. What is wrong?

Show the answer

Answer: a

The Markov assumption needs everything that matters for what happens next in the state.

Check yourself

What does Q^π(s, a) measure that V^π(s) doesn't?

Show the answer

Answer: a

V averages over the policy's own first action; Q fixes the first action. V^π(s) = Σa π(a∣s) Q^π(s, a).

Check yourself

Why can CodeSplash score a learned policy against the optimal one in the Policy learning studio?

Show the answer

Answer: a

With the table known, the Bellman backup gives the exact optimum. Real problems rarely allow that.

09

Recap

Recap
  • An MDP has states, actions, transitions, rewards and a discount; the state must carry what matters.
  • V(s) and Q(s, a) are expected discounted returns; the Bellman equation ties each to the next step.
  • Value iteration solves a small, known MDP exactly.
  • The Policy learning studio's environments have exact optimal values, so learned policies get an honest score.

Concepts in this lesson