Skip to content

Learn a policy from logged episodes

Learn a decision policy from logged episodes with fitted Q iteration, behavior cloning, conservative Q-learning or implicit Q-learning, and judge it against a behavior-cloning baseline before trusting it.

Advanced ~15 min9 steps

What runs in CodeSplash

You will be able to

  • Do one step of fitted Q iteration by hand
  • Say why offline learners must stay near the logged actions, and how CQL and IQL do it
  • Read a learned policy's evaluation, agreement and support share

Read first

01

Learning without trying anything new

Read

Offline policy learningOffline policy learningLearns a decision policy from logged episodes only, without trying new actions; it can only be trusted where the logs tried them. looks only at logged episodes. It can't try an action to see what happens; it can only recombine what the logs show. That is its strength (no risky experiments) and its limit (no evidence for actions the logs never took).

02

Fitted Q iteration, one step at a time

Read

Fitted Q iterationFitted Q iterationRepeats a regression of reward plus the best next value until the Q-model settles; the policy picks the action with the highest Q. learns Q(s, a), the return of taking action a in state s and acting well afterwards. Each round fits a regression of

y=r+γmax⁡a′Q^(s′,a′)y = r + \gamma \max_{a'} \hat Q(s', a')

on the logged state and action, then repeats with the new Q until nothing changes. The policy picks the action with the highest Q.

03

Compute one target

Checkpoint

Check yourself

A logged transition earned reward 1 and led to a state where the current Q-model gives 1.5 for "wait" and 2 for "act". With discount 0.9, what target does fitted Q iteration regress this transition on?

Show the answer

Answer: 2.8

y = 1 + 0.9 × max(1.5, 2) = 1 + 0.9 × 2 = 2.8. The max picks the better next action even if the logs never took it there, which is where offline learners get into trouble.

04

Stay where the logs have been

Predict

Predict first

The max in the target picks whichever next action the model rates highest. For an action the logs rarely took, the model's estimate is mostly noise. What does taking the max of noisy estimates tend to do?

It underestimatesIt overestimatesIt is unbiased
Reveal

It overestimates: the max favors whichever estimates happen to be too high, and the policy then chooses those actions. Conservative methods push back on this.

05

Three ways to stay close

Read
  • Behavior cloningBehavior cloningLearns to copy the logged actions from the states (here a multinomial logistic regression): a baseline every learned policy should beat. copies the logged actions. It rarely does much better than the logging policy, but it rarely does worse; every other learner is compared with it.
  • Conservative Q-learningConservative Q-learningA Q-network trained with a penalty that pushes down values of actions the logs rarely took, so the policy stays near logged behavior. adds a penalty that lowers Q for actions the logs rarely took (α sets how much). Double targets curb the overestimation the max causes.
  • Implicit Q-learningImplicit Q-learningLearns values only from logged actions (an expectile of their Q), then imitates logged actions weighted by exp(β × advantage). never takes a max over actions: it learns values from logged actions only and then imitates the logged actions with high advantage.
06

Read a result

In the app
Offline policy learning (Fitted Q iteration)Recorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

Fitted Q iteration learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.511, 95% CI [0.494, 0.529], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 64% of the logged states.

Learned policy value (FQE)
0.5107
95% CI
[0.4940, 0.5289]
Logged policy value
0.0487
Agreement with logged actions
0.6406

Plots

Estimated return per episodeHow large are several estimates, how precise, and which exclude the null?
View data
ValueUpperPolicy and estimatorLower
0.51070.5289Fitted Q iteration · Fitted Q evaluation0.4940
0.53230.5866Fitted Q iteration · Weighted doubly robust0.4717
0.51850.6622Fitted Q iteration · Weighted per-decision IS−0.2262
0.51070.5289Behavior cloning (baseline) · Fitted Q evaluation0.4940
0.53230.5866Behavior cloning (baseline) · Weighted doubly robust0.4717
0.51850.6622Behavior cloning (baseline) · Weighted per-decision IS−0.2262
0.04870.1387Logged policy · Observed return−0.0376
Estimated start-state value by iterationHow does a policy's return change as training goes on, and does it beat the policy that logged the data?
View data
IterationEstimated value
1−0.0404
2−0.0736
3−0.1034
4−0.0104
50.1554
60.3249
70.4345
80.4823
90.5001
100.5067
110.5094
120.5107
130.5113
140.5117
150.5118
160.5119
170.5120
180.5120
190.5120
200.5120
210.5120
220.5120
230.5120
240.5120
250.5120
260.5120
270.5120
280.5120
290.5120
300.5120
310.5120
320.5120
330.5120
340.5120
350.5120
360.5120
370.5120
Action shares: logged vs learnedHow often does the learned policy choose each action, compared with the logged policy?
View data
ActionSharePolicy
left0.1688Logged
stay0.1906Logged
right0.6406Logged
left0Learned
stay0Learned
right1Learned

Estimated return per episode

PolicyEstimatorEstimate95% CI low95% CI high
Fitted Q iterationFitted Q evaluation0.51070.49400.5289
Fitted Q iterationWeighted doubly robust0.53230.47170.5866
Fitted Q iterationWeighted per-decision IS0.5185−0.22620.6622
Behavior cloning (baseline)Fitted Q evaluation0.51070.49400.5289
Behavior cloning (baseline)Weighted doubly robust0.53230.47170.5866
Behavior cloning (baseline)Weighted per-decision IS0.5185−0.22620.6622
Logged policyObserved return0.0487−0.03760.1387

Learned policy by state (12 of 12 distinct states)

cellweather todayLearned actionQ(left)Q(stay)Q(right)
c1sunright0.34940.43980.5287
c2sunright0.44480.52780.6198
c3rainright0.52200.61870.6798
c4rainright0.61640.72270.7901
c5rainright0.73100.83310.9077
c1rainright0.34470.43610.4884
c0sunright0.36530.36050.4423
c3sunright0.52670.62240.7202
c2rainright0.44010.52410.5794
c4sunright0.62110.72630.8305
c5sunright0.73570.83670.9480
c0rainright0.36060.35680.4019

Actions: logged vs learned policy

actionLogged shareLearned share
left16.9%0.0%
stay19.1%0.0%
right64.1%100.0%

Training by iteration

IterationLossEstimated start-state value
10.0104−0.0404
20.0085−0.0736
30.0063−0.1034
40.0053−0.0104
50.00460.1554
60.00370.3249
70.00250.4345
80.00150.4823
90.00110.5001
100.00090.5067
110.00090.5094
120.00090.5107
130.00090.5113
140.00090.5117
150.00080.5118
160.00080.5119
170.00080.5120
180.00080.5120
190.00080.5120
200.00080.5120
210.00080.5120
220.00080.5120
230.00080.5120
240.00080.5120
250.00080.5120
260.00080.5120
270.00080.5120
280.00080.5120
290.00080.5120
300.00080.5120
310.00080.5120
320.00080.5120
330.00080.5120
340.00080.5120
350.00080.5120
360.00080.5120
370.00080.5120
  • 18 of 60 episodes end without done = true (cut short): their last step is left out of the Q-models because its next state is unknown.
  • Effective sample size 2.5 of 60 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
  • The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
  • Fitted Q iteration; discount 0.95; Q-models and evaluation use cell, weather today. Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact R script · R R version 4.5.1 (2025-06-13)
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec 10dbaa8e2b656318
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bandit_design(), cs_seq_*(), cs_orl_*(): twins of codesplash.decide.ope / sequential / offline_rl

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pol_corridor.parquet", col_select = c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done")))
n_input <- nrow(df)
df[["cell"]] <- factor(df[["cell"]], levels = c("c0", "c1", "c2", "c3", "c4", "c5"))  # stored level order
df[["weather today"]] <- factor(df[["weather today"]], levels = c("rain", "sun"))  # stored level order
df[["action"]] <- factor(df[["action"]], levels = c("left", "stay", "right"))  # stored level order
df[["done"]] <- factor(df[["done"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col <- "episode"
step_col <- "step"
a_col <- "action"
r_col <- "reward"
p_col <- "propensity"
done_col <- "done"
features <- c("cell", "weather today")
algorithm <- "fqi" # fqi | bc | cql | iql
gamma <- as.numeric(0.95)
iterations <- as.integer(300)
rounds <- as.integer(20)
hidden <- as.integer(unlist(c(32, 32)))
epochs <- as.integer(20)
lr <- as.numeric(0.005)
batch_size <- 256
alpha <- as.numeric(1)
double <- TRUE
dueling <- FALSE
expectile <- as.numeric(0.7)
temperature <- as.numeric(3)
folds <- as.integer(2)
fqe_iterations <- as.integer(200)
n_boot <- as.integer(200)
conf <- 0.95
seed <- 42

# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0

# Rows by episode (first appearance), then step.
ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
ord <- cs_seq_order(cs_seq_episode_codes(ep_keys), as.numeric(df[[step_col]]))
df <- df[ord, , drop = FALSE]
rownames(df) <- NULL
ep <- cs_seq_episode_codes(ep_keys[ord])
st <- cs_seq_structure(ep, as.numeric(df[[step_col]]), if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL)
lv <- levels(df[[a_col]])
K <- length(lv)
action <- as.character(df[[a_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) else as.numeric(df[[r_col]])
propensity <- if (!is.null(p_col)) as.numeric(df[[p_col]]) else NULL
is_cat <- vapply(features, function(c) is.factor(df[[c]]), logical(1))
numeric_f <- features[!is_cat]
categorical_f <- lapply(stats::setNames(features[is_cat], features[is_cat]), function(c) levels(df[[c]]))

# %% Checks (same order in both engines)
if (st$duplicates > 0) cs_error("CS_E_INVALID_VALUES", column = step_col, requirement = "unique within each episode", count = st$duplicates)
if (!is.null(propensity)) {
  bad <- sum(propensity <= 0 | propensity > 1)
  if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = p_col, requirement = "a probability in (0, 1]", count = bad)
}
if (st$E < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = ep_col, min = 2, k = st$E)
present <- length(unique(action))
if (present < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = a_col, min = 2, k = present)
a_idx <- match(action, lv)
x <- cs_bandit_design(df, numeric_f, categorical_f)
starts <- st$starts
fit_rows <- st$fit_rows

# %% Learn
q_all <- NULL
probs_all <- NULL
bc <- cs_seq_behavior_cloning(x, a_idx, K)
bc_policy <- as.integer(apply(bc$probs, 1, which.max))
extra <- list()
if (algorithm == "fqi") {
  fq <- cs_seq_fitted_q(x, a_idx, reward, st$nxt, K, gamma, fit_rows, iterations, starts = starts)
  q_all <- x %*% t(fq$beta)
  policy <- cs_seq_greedy(q_all, fq$support)
  trace <- fq$trace
  iters_run <- fq$iterations
  if (!fq$converged) warnings <- c(warnings, sprintf("Fitted Q iteration did not settle within %d iterations; raise the limit or lower the discount.", iterations))
} else if (algorithm == "bc") {
  probs_all <- bc$probs
  policy <- bc_policy
  trace <- bc$trace
  iters_run <- bc$iterations
  if (!bc$converged) warnings <- c(warnings, sprintf("Behavior cloning did not converge within %d Newton steps.", iters_run))
} else {
  z <- cs_seq_nn_features(x, length(numeric_f))
  if (algorithm == "cql") {
    fit <- cs_orl_cql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
    q_all <- cs_orl_q_values(fit$params, z, dueling, K)
    policy <- as.integer(apply(q_all, 1, which.max))
  } else {
    fit <- cs_orl_iql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
    q_all <- cs_orl_q_values(fit$params, z, FALSE, K)
    policy <- as.integer(apply(cs_orl_policy_logits(fit$policy_params, z), 1, which.max))
    extra <- list(weight_ess = fit$weight_ess, weight_capped = fit$weight_capped)
    if (fit$weight_capped > 0.05) {
      warnings <- c(warnings, sprintf("%.0f%% of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.", fit$weight_capped * 100))
    }
  }
  trace <- fit$trace
  iters_run <- rounds
}

# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev <- cs_seq_evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc <- if (algorithm != "bc") cs_seq_evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) else NULL
E <- ev$E
n <- ev$n
agreement <- mean(policy == a_idx)
low_support <- mean(bc$probs[cbind(seq_len(n), policy)] < 0.05)
if (st$truncated > 0) {
  warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true (cut short): their last step is left out of the Q-models because its next state is unknown.", st$truncated, E, done_col))
}
if (low_support > 0.2) {
  warnings <- c(warnings, sprintf("At %.0f%% of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%%): its value there is extrapolated.", low_support * 100))
}
if (!ev$fqe_converged) warnings <- c(warnings, sprintf("Fitted Q evaluation of the learned policy did not settle within %d iterations.", fqe_iterations))
if (!is.null(propensity) && ev$ess < 0.1 * E) {
  warnings <- c(warnings, sprintf("Effective sample size %.1f of %d episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.", ev$ess, E))
}
warnings <- c(warnings, "The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")

# %% Result
alg_label <- c(fqi = "Fitted Q iteration", bc = "Behavior cloning", cql = "Conservative Q-learning", iql = "Implicit Q-learning")[[algorithm]]
pct <- sprintf("%.0f%%", conf * 100)
v_fqe <- ev$estimate$fqe
v_ci <- ev$ci$fqe
logged <- ev$logged
gfmt <- format(gamma, digits = 6)
summary <- sprintf(
  "%s learned a policy from %s episodes (%s decisions). Fitted Q evaluation puts its return per episode at %.3f, %s CI [%.3f, %.3f], against %.3f for the logged policy (discount %s). It agrees with the logged action at %.0f%% of the logged states.",
  alg_label, format(E, big.mark = ","), format(n, big.mark = ","), v_fqe, pct, v_ci[1], v_ci[2], logged, gfmt, agreement * 100
)
lab <- cs_seq_labels()
eval_rows <- list()
for (pair in list(list(alg_label, ev), list("Behavior cloning (baseline)", ev_bc))) {
  res <- pair[[2]]
  if (is.null(res)) next
  for (e in intersect(c("fqe", "wdr", "wpdis"), names(res$estimate))) {
    eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = pair[[1]], estimator = lab[[e]], estimate = res$estimate[[e]],
                                                      low = res$ci[[e]][1], high = res$ci[[e]][2])
  }
}
eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = "Logged policy", estimator = "Observed return", estimate = logged,
                                                  low = ev$logged_ci[1], high = ev$logged_ci[2])
eval_df <- do.call(rbind, eval_rows)
values <- list(policy_value = v_fqe, policy_ci_low = v_ci[1], policy_ci_high = v_ci[2], logged_value = logged,
               logged_ci_low = ev$logged_ci[1], logged_ci_high = ev$logged_ci[2], agreement = agreement, low_support_share = low_support,
               n_episodes = E, n_steps = n, iterations_run = iters_run, final_loss = if (length(trace)) trace[[length(trace)]]$loss else NULL,
               algorithm = algorithm)
if ("wdr" %in% names(ev$estimate)) {
  values$policy_value_wdr <- ev$estimate$wdr
  values$policy_wdr_ci_low <- ev$ci$wdr[1]
  values$policy_wdr_ci_high <- ev$ci$wdr[2]
  values$ess <- ev$ess
}
if (!is.null(ev_bc)) values$bc_value <- ev_bc$estimate$fqe
values <- c(values, extra)
# Policy table: one row per distinct state (first appearance).
ds <- cs_seq_distinct_states(x)
values$n_states <- ds$count
score <- if (!is.null(q_all)) q_all else probs_all
score_label <- if (!is.null(q_all)) "Q" else "P"
pol_cols <- lapply(seq_along(features), function(j) list(key = sprintf("s%d", j), label = features[j], type = if (is_cat[j]) "string" else "number"))
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("%s(%s)", score_label, lv[j]), type = "number")
pol_df <- data.frame(row.names = seq_along(ds$rows))
for (j in seq_along(features)) {
  c <- features[j]
  pol_df[[sprintf("s%d", j)]] <- if (is_cat[j]) as.character(df[[c]][ds$rows]) else as.numeric(df[[c]][ds$rows])
}
pol_df$action <- lv[policy[ds$rows]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(score[ds$rows, j])
rownames(pol_df) <- NULL
share_df <- data.frame(action = lv, logged = vapply(seq_len(K), function(j) mean(a_idx == j), numeric(1)),
                       learned = vapply(seq_len(K), function(j) mean(policy == j), numeric(1)))
train_value <- lapply(trace, function(t) t$value)
train_df <- data.frame(iteration = vapply(trace, function(t) as.integer(t$iteration), integer(1)),
                       loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)))
train_df$value <- if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) unlist(train_value) else rep(NA_real_, nrow(train_df))
eval_labels <- paste(eval_df$policy, eval_df$estimator, sep = " · ")
charts <- list(
  cs_chart("evaluation", "forest", "Estimated return per episode", list(
    label = cs_col("Policy and estimator", eval_labels, levels = eval_labels),
    estimate = cs_col("Value", eval_df$estimate),
    low = cs_col("Lower", eval_df$low),
    high = cs_col("Upper", eval_df$high)
  ), controls = list(reference = logged)),
  cs_chart("actions", "share-compare", "Action shares: logged vs learned", list(
    level = cs_col("Action", c(share_df$action, share_df$action), levels = lv),
    share = cs_col("Share", c(share_df$logged, share_df$learned)),
    source = cs_col("Policy", c(rep("Logged", K), rep("Learned", K)), levels = c("Logged", "Learned"))
  ), question = "How often does the learned policy choose each action, compared with the logged policy?")
)
if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) {
  charts <- append(charts, list(cs_chart("training", "return-curve", "Estimated start-state value by iteration", list(
    x = cs_col("Iteration", train_df$iteration),
    y = cs_col("Estimated value", train_df$value)
  ), controls = list(reference = logged))), after = 1L)
}
net_note <- if (algorithm %in% c("cql", "iql")) {
  sprintf(" (networks: hidden layers %s, %d rounds × %d epochs, learning rate %s)", paste(hidden, collapse = ", "), rounds, epochs, format(lr, digits = 6))
} else ""
cs_publish(list(
  method = "decide.offline_rl",
  methodVersion = "1.1.0",
  title = sprintf("Offline policy learning (%s)", alg_label),
  engine = cs_engine_info("stats", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "policy_value", label = "Learned policy value (FQE)", value = v_fqe),
    list(key = "ci", label = paste(pct, "CI"), value = v_ci),
    list(key = "logged", label = "Logged policy value", value = logged),
    list(key = "agreement", label = "Agreement with logged actions", value = agreement)
  ),
  tables = list(
    list(key = "evaluation", title = "Estimated return per episode",
         columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "estimator", label = "Estimator", type = "string"),
                        list(key = "estimate", label = "Estimate", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
                        list(key = "high", label = paste(pct, "CI high"), type = "number")),
         rows = eval_df),
    list(key = "policy", title = sprintf("Learned policy by state (%d of %d distinct states)", min(ds$count, 500L), ds$count), columns = pol_cols, rows = pol_df),
    list(key = "actions", title = "Actions: logged vs learned policy",
         columns = list(list(key = "action", label = a_col, type = "string"), list(key = "logged", label = "Logged share", type = "percent"),
                        list(key = "learned", label = "Learned share", type = "percent")),
         rows = share_df),
    list(key = "training", title = "Training by iteration",
         columns = list(list(key = "iteration", label = "Iteration", type = "integer"), list(key = "loss", label = "Loss", type = "number"),
                        list(key = "value", label = "Estimated start-state value", type = "number")),
         rows = train_df)
  ),
  warnings = warnings,
  notes = list(paste0(alg_label, "; discount ", gfmt, "; Q-models and evaluation use ", paste(features, collapse = ", "), net_note,
                      sprintf(". Evaluation: fitted Q evaluation (linear per action, cross-fitted over %d episode folds)", folds),
                      if (!is.null(propensity)) ", weighted doubly robust and weighted per-decision IS with the logged propensities" else "",
                      sprintf("; %d bootstrap resamples of episodes (seed %s). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.", n_boot, seed))),
  values = values,
  charts = charts
))
Python

Fitted Q iteration learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.511, 95% CI [0.494, 0.529], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 64% of the logged states.

Learned policy value (FQE)
0.5107
95% CI
[0.4940, 0.5289]
Logged policy value
0.0487
Agreement with logged actions
0.6406

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

Estimated return per episode

PolicyEstimatorEstimate95% CI low95% CI high
Fitted Q iterationFitted Q evaluation0.51070.49400.5289
Fitted Q iterationWeighted doubly robust0.53230.47170.5866
Fitted Q iterationWeighted per-decision IS0.5185−0.22620.6622
Behavior cloning (baseline)Fitted Q evaluation0.51070.49400.5289
Behavior cloning (baseline)Weighted doubly robust0.53230.47170.5866
Behavior cloning (baseline)Weighted per-decision IS0.5185−0.22620.6622
Logged policyObserved return0.0487−0.03760.1387

Learned policy by state (12 of 12 distinct states)

cellweather todayLearned actionQ(left)Q(stay)Q(right)
c1sunright0.34940.43980.5287
c2sunright0.44480.52780.6198
c3rainright0.52200.61870.6798
c4rainright0.61640.72270.7901
c5rainright0.73100.83310.9077
c1rainright0.34470.43610.4884
c0sunright0.36530.36050.4423
c3sunright0.52670.62240.7202
c2rainright0.44010.52410.5794
c4sunright0.62110.72630.8305
c5sunright0.73570.83670.9480
c0rainright0.36060.35680.4019

Actions: logged vs learned policy

actionLogged shareLearned share
left16.9%0.0%
stay19.1%0.0%
right64.1%100.0%

Training by iteration

IterationLossEstimated start-state value
10.0104−0.0404
20.0085−0.0736
30.0063−0.1034
40.0053−0.0104
50.00460.1554
60.00370.3249
70.00250.4345
80.00150.4823
90.00110.5001
100.00090.5067
110.00090.5094
120.00090.5107
130.00090.5113
140.00090.5117
150.00080.5118
160.00080.5119
170.00080.5120
180.00080.5120
190.00080.5120
200.00080.5120
210.00080.5120
220.00080.5120
230.00080.5120
240.00080.5120
250.00080.5120
260.00080.5120
270.00080.5120
280.00080.5120
290.00080.5120
300.00080.5120
310.00080.5120
320.00080.5120
330.00080.5120
340.00080.5120
350.00080.5120
360.00080.5120
370.00080.5120
  • 18 of 60 episodes end without done = true (cut short): their last step is left out of the Q-models because its next state is unknown.
  • Effective sample size 2.5 of 60 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
  • The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
  • Fitted Q iteration; discount 0.95; Q-models and evaluation use cell, weather today. Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec 10dbaa8e2b656318
# Dataset: pol_corridor (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.decide import ope, sequential as seq  # twins of codesplashr::cs_bandit_design / cs_seq_* (shared-RNG folds and bootstrap)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"])
n_input = len(df)
df["cell"] = pd.Categorical(df["cell"], categories=["c0", "c1", "c2", "c3", "c4", "c5"])  # stored level order
df["weather today"] = pd.Categorical(df["weather today"], categories=["rain", "sun"])  # stored level order
df["action"] = pd.Categorical(df["action"], categories=["left", "stay", "right"])  # stored level order
df["done"] = pd.Categorical(df["done"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"])  # listwise deletion over the analysis columns
df["cell"] = df["cell"].cat.remove_unused_categories()
df["weather today"] = df["weather today"].cat.remove_unused_categories()
df["action"] = df["action"].cat.remove_unused_categories()
df["done"] = df["done"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["episode", "step", "cell", "weather today", "action", "reward", "propensity", "done"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col, step_col, a_col, r_col = "episode", "step", "action", "reward"
p_col = "propensity"
done_col = "done"
features = ["cell", "weather today"]
algorithm = "fqi"  # fqi | bc | cql | iql
gamma = float(0.95)
iterations = int(300)
rounds = int(20)
hidden = [int(u) for u in [32, 32]]
epochs = int(20)
lr = float(0.005)
batch_size = 256
alpha = float(1)
double = True
dueling = False
expectile = float(0.7)
temperature = float(3)
folds = int(2)
fqe_iterations = int(200)
n_boot = int(200)
conf = 0.95
seed = 42


def as_flag(s):
    """Yes/no columns count as 1/0."""
    return (s.astype(str) == "true").to_numpy() if isinstance(s.dtype, pd.CategoricalDtype) else (s.to_numpy(dtype=float) != 0)


# Rows by episode (first appearance), then step.
ep_keys = df[ep_col].astype(str).tolist() if isinstance(df[ep_col].dtype, pd.CategoricalDtype) else df[ep_col].to_numpy(dtype=float).tolist()
order = seq.order_rows(seq.episode_codes(ep_keys), df[step_col].to_numpy(dtype=float))
df = df.iloc[order].reset_index(drop=True)
ep_keys = [ep_keys[i] for i in order]
ep = seq.episode_codes(ep_keys)
st = seq.structure(ep, df[step_col].to_numpy(dtype=float), as_flag(df[done_col]) if done_col else None)
levels = [str(x) for x in df[a_col].cat.categories]
K = len(levels)
action = df[a_col].astype(str).to_numpy()
reward = as_flag(df[r_col]).astype(float) if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
propensity = df[p_col].to_numpy(dtype=float) if p_col else None
numeric = [c for c in features if not isinstance(df[c].dtype, pd.CategoricalDtype)]
categorical = {c: [str(x) for x in df[c].cat.categories] for c in features if isinstance(df[c].dtype, pd.CategoricalDtype)}

# %% Checks (same order in both engines)
if st["duplicates"]:
    cs.cs_error("CS_E_INVALID_VALUES", column=step_col, requirement="unique within each episode", count=st["duplicates"])
if propensity is not None:
    bad = int(np.sum((propensity <= 0) | (propensity > 1)))
    if bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=p_col, requirement="a probability in (0, 1]", count=bad)
if st["E"] < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=ep_col, min=2, k=st["E"])
present = len(set(action.tolist()))
if present < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=a_col, min=2, k=present)
col_of = {lv: j for j, lv in enumerate(levels)}
a_idx = np.array([col_of[a] for a in action], dtype=np.int64)
x = ope.design(df, numeric, categorical)
starts = st["starts"]
fit_rows = st["fit_rows"]

# %% Learn
q_all = None
probs_all = None
bc = seq.behavior_cloning(x, a_idx, K)
bc_policy = np.argmax(bc["probs"], axis=1)
extra = {}
if algorithm == "fqi":
    beta, support, iters_run, converged, trace = seq.fitted_q(x, a_idx, reward, st["next"], K, gamma, fit_rows, iterations, starts=starts)
    q_all = seq.q_values(x, beta)
    policy = seq.greedy(q_all, support)
    if not converged:
        warnings.append(f"Fitted Q iteration did not settle within {iterations} iterations; raise the limit or lower the discount.")
elif algorithm == "bc":
    probs_all = bc["probs"]
    policy = bc_policy
    trace = bc["trace"]
    iters_run, converged = bc["iterations"], bc["converged"]
    if not converged:
        warnings.append(f"Behavior cloning did not converge within {iters_run} Newton steps.")
else:
    z = seq.nn_features(x, len(numeric))
    if algorithm == "cql":
        fit = orl.cql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
        q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, dueling, K)
        policy = np.argmax(q_all, axis=1)
    else:
        fit = orl.iql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
        q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, False, K)
        policy = np.argmax(orl.policy_logits(fit["policy_params"], z), axis=1)
        extra = {"weight_ess": fit["weight_ess"], "weight_capped": fit["weight_capped"]}
        if fit["weight_capped"] > 0.05:
            warnings.append(f"{fit['weight_capped']:.0%} of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.")
    trace = fit["trace"]
    iters_run, converged = rounds, True

# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev = seq.evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc = seq.evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) if algorithm != "bc" else None
E, n = ev["E"], ev["n"]
agreement = float(np.mean(policy == a_idx))
low_support = float(np.mean(bc["probs"][np.arange(n), policy] < 0.05))
if st["truncated"]:
    warnings.append(f"{st['truncated']} of {E} episodes end without {done_col} = true (cut short): their last step is left out of the Q-models because its next state is unknown.")
if low_support > 0.2:
    warnings.append(f"At {low_support:.0%} of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%): its value there is extrapolated.")
if not ev["fqe_converged"]:
    warnings.append(f"Fitted Q evaluation of the learned policy did not settle within {fqe_iterations} iterations.")
if propensity is not None and ev["ess"] < 0.1 * E:
    warnings.append(f"Effective sample size {ev['ess']:.1f} of {E} episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.")
warnings.append("The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")

# %% Result
alg_label = {"fqi": "Fitted Q iteration", "bc": "Behavior cloning", "cql": "Conservative Q-learning", "iql": "Implicit Q-learning"}[algorithm]
pct = f"{conf:.0%}"
v_fqe, (v_lo, v_hi) = ev["estimate"]["fqe"], ev["ci"]["fqe"]
logged = ev["logged"]
summary = (
    f"{alg_label} learned a policy from {E:,} episodes ({n:,} decisions). Fitted Q evaluation puts its return per episode at {v_fqe:.3f}, "
    f"{pct} CI [{v_lo:.3f}, {v_hi:.3f}], against {logged:.3f} for the logged policy (discount {gamma:g}). It agrees with the logged action at "
    f"{agreement:.0%} of the logged states."
)
eval_rows = []
for name, res in [(alg_label, ev), ("Behavior cloning (baseline)", ev_bc)]:
    if res is None:
        continue
    for e in [k for k in ("fqe", "wdr", "wpdis") if k in res["estimate"]]:
        eval_rows.append({"policy": name, "estimator": seq.LABELS[e], "estimate": res["estimate"][e], "low": res["ci"][e][0], "high": res["ci"][e][1]})
eval_rows.append({"policy": "Logged policy", "estimator": "Observed return", "estimate": logged, "low": ev["logged_ci"][0], "high": ev["logged_ci"][1]})
values = {"policy_value": v_fqe, "policy_ci_low": v_lo, "policy_ci_high": v_hi, "logged_value": logged, "logged_ci_low": ev["logged_ci"][0],
          "logged_ci_high": ev["logged_ci"][1], "agreement": agreement, "low_support_share": low_support, "n_episodes": E, "n_steps": n,
          "iterations_run": iters_run, "final_loss": trace[-1]["loss"] if trace else None, "algorithm": algorithm}
if "wdr" in ev["estimate"]:
    values.update({"policy_value_wdr": ev["estimate"]["wdr"], "policy_wdr_ci_low": ev["ci"]["wdr"][0], "policy_wdr_ci_high": ev["ci"]["wdr"][1], "ess": ev["ess"]})
if ev_bc is not None:
    values["bc_value"] = ev_bc["estimate"]["fqe"]
values.update(extra)
# Policy table: one row per distinct state (first appearance).
first, n_states = seq.distinct_states(x)
values["n_states"] = n_states
pol_cols = [{"key": f"s{j + 1}", "label": c, "type": "string" if c in categorical else "number"} for j, c in enumerate(features)]
pol_cols.append({"key": "action", "label": "Learned action", "type": "string"})
score = q_all if q_all is not None else probs_all
score_label = "Q" if q_all is not None else "P"
for j, lv in enumerate(levels):
    pol_cols.append({"key": f"v{j + 1}", "label": f"{score_label}({lv})", "type": "number"})
pol_rows = []
for i in first:
    r = {f"s{j + 1}": (str(df[c].iloc[i]) if c in categorical else float(df[c].iloc[i])) for j, c in enumerate(features)}
    r["action"] = levels[int(policy[i])]
    for j in range(K):
        r[f"v{j + 1}"] = float(score[i, j])
    pol_rows.append(r)
share_rows = [{"action": lv, "logged": float(np.mean(a_idx == j)), "learned": float(np.mean(policy == j))} for j, lv in enumerate(levels)]
train_value = [t.get("value") for t in trace]
charts = [
    cs.chart("evaluation", "forest", "Estimated return per episode", {
        "label": cs.col("Policy and estimator", [f"{r['policy']} · {r['estimator']}" for r in eval_rows], levels=[f"{r['policy']} · {r['estimator']}" for r in eval_rows]),
        "estimate": cs.col("Value", [r["estimate"] for r in eval_rows]),
        "low": cs.col("Lower", [r["low"] for r in eval_rows]),
        "high": cs.col("Upper", [r["high"] for r in eval_rows]),
    }, controls={"reference": logged}),
    cs.chart("actions", "share-compare", "Action shares: logged vs learned", {
        "level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=levels),
        "share": cs.col("Share", [r["logged"] for r in share_rows] + [r["learned"] for r in share_rows]),
        "source": cs.col("Policy", ["Logged"] * K + ["Learned"] * K, levels=["Logged", "Learned"]),
    }, question="How often does the learned policy choose each action, compared with the logged policy?"),
]
if all(v is not None for v in train_value) and train_value:
    charts.insert(1, cs.chart("training", "return-curve", "Estimated start-state value by iteration", {
        "x": cs.col("Iteration", [t["iteration"] for t in trace]),
        "y": cs.col("Estimated value", train_value),
    }, controls={"reference": logged}))
cs.publish({
    "method": "decide.offline_rl",
    "methodVersion": "1.1.0",
    "title": f"Offline policy learning ({alg_label})",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "policy_value", "label": "Learned policy value (FQE)", "value": v_fqe},
        {"key": "ci", "label": f"{pct} CI", "value": [v_lo, v_hi]},
        {"key": "logged", "label": "Logged policy value", "value": logged},
        {"key": "agreement", "label": "Agreement with logged actions", "value": agreement},
    ],
    "tables": [
        {"key": "evaluation", "title": "Estimated return per episode",
         "columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "estimator", "label": "Estimator", "type": "string"},
                     {"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
                     {"key": "high", "label": f"{pct} CI high", "type": "number"}],
         "rows": eval_rows},
        {"key": "policy", "title": f"Learned policy by state ({min(n_states, 500)} of {n_states} distinct states)", "columns": pol_cols, "rows": pol_rows},
        {"key": "actions", "title": "Actions: logged vs learned policy",
         "columns": [{"key": "action", "label": a_col, "type": "string"}, {"key": "logged", "label": "Logged share", "type": "percent"},
                     {"key": "learned", "label": "Learned share", "type": "percent"}],
         "rows": share_rows},
        {"key": "training", "title": "Training by iteration",
         "columns": [{"key": "iteration", "label": "Iteration", "type": "integer"}, {"key": "loss", "label": "Loss", "type": "number"},
                     {"key": "value", "label": "Estimated start-state value", "type": "number"}],
         "rows": [{"iteration": t["iteration"], "loss": t["loss"], "value": t.get("value")} for t in trace]},
    ],
    "warnings": warnings,
    "notes": [
        f"{alg_label}; discount {gamma:g}; Q-models and evaluation use {', '.join(features)}"
        + (f" (networks: hidden layers {', '.join(str(h) for h in hidden)}, {rounds} rounds × {epochs} epochs, learning rate {lr:g})" if algorithm in ("cql", "iql") else "")
        + f". Evaluation: fitted Q evaluation (linear per action, cross-fitted over {folds} episode folds)"
        + (", weighted doubly robust and weighted per-decision IS with the logged propensities" if propensity is not None else "")
        + f"; {n_boot} bootstrap resamples of episodes (seed {seed}). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.",
    ],
    "values": values,
    "charts": charts,
})

Fitted Q iteration learned a policy over 12 distinct states. Fitted Q evaluation puts its return at 0.511 per episode, against 0.049 for the logged policy and 0.511 for the behavior-cloning baseline. It agrees with the logged action at 64.1% of the logged states.

The share of states with low supportShare of states with low supportShare of logged states where the learned policy picks an action the logging policy rarely took (estimated probability under 5%). is 0.0%: where the learned policy picks actions the logs rarely took, its value is the model's extrapolation.

07

Check your understanding

Checkpoint

Check yourself

The learned policy's estimated value beats the logged policy's by a wide margin. Why is that number optimistic?

Show the answer

Answer: b

Selecting and evaluating on the same data rewards the policy for exploiting noise. Test it on new episodes, in a simulated environment (the Policy learning studio scores environment policies exactly), or with a small live trial.

Check yourself

You raise conservative Q-learning's α from 0.5 to 5. What do you expect?

Show the answer

Answer: a

A larger penalty makes rarely logged actions look worse, so the policy stays near behavior cloning. Try a few values: a policy that only beats the logs at small α rests on extrapolation.

08

Try it

In the app

In the Policy learning studio, choose logged episodes or a built-in environment, then Learn. Start with fitted Q iteration on a categorical state; compare with behavior cloning before trying the neural learners.

Python
import numpy as np
import pandas as pd

# Tabular fitted Q iteration: one Q value per (state, action).
df = pd.read_csv("episodes.csv").sort_values(["episode", "step"])
nxt = df.groupby("episode")["state"].shift(-1)
states, actions = sorted(df["state"].unique()), sorted(df["action"].unique())
Q = pd.DataFrame(0.0, index=states, columns=actions)
gamma = 0.95
for _ in range(500):
    v_next = nxt.map(Q.max(axis=1)).fillna(0.0)
    y = df["reward"] + gamma * v_next
    new = y.groupby([df["state"], df["action"]]).mean().unstack().reindex(index=states, columns=actions).fillna(0.0)
    if np.abs(new - Q).to_numpy().max() < 1e-10:
        break
    Q = new
print(Q.idxmax(axis=1))
R
df <- read.csv("episodes.csv", check.names = FALSE)
df <- df[order(df$episode, df$step), ]
df$next_state <- ave(df$state, df$episode, FUN = function(s) c(s[-1], NA))
Q <- tapply(df$reward, list(df$state, df$action), function(x) 0)
Q[] <- 0
gamma <- 0.95
for (i in 1:500) {
  v_next <- ifelse(is.na(df$next_state), 0, apply(Q, 1, max)[as.character(df$next_state)])
  y <- df$reward + gamma * v_next
  new <- tapply(y, list(df$state, df$action), mean)
  new[is.na(new)] <- 0
  if (max(abs(new - Q)) < 1e-10) break
  Q <- new
}
colnames(Q)[apply(Q, 1, which.max)]
09

Recap

Recap
  • Offline learners recombine logged experience; they have no evidence for actions the logs never took.
  • Fitted Q iteration is transparent and exact for a categorical state; its max can overestimate rarely taken actions.
  • Conservative Q-learning penalizes those actions; implicit Q-learning avoids the max; behavior cloning is the baseline to beat.
  • A learned policy's value on its own training episodes is optimistic: confirm it on new episodes or in a simulated environment.

Concepts in this lesson