Skip to content

When a policy learns, who does it serve?

Personalize decisions with contextual bandits, judge them by replaying randomized logs, and ask who pays for the learning.

Advanced ~12 min10 steps

What runs in CodeSplash

You will be able to

  • Say what a contextual bandit adds to a plain bandit
  • Read a replay evaluation, and judge it against its baseline and its noise
  • Check who benefits from a learning policy, and who bears its exploration

Read first

01

From best overall to best for whom

Read

A plain bandit looks for the single best option. A contextual banditContextual banditA bandit that uses features of each user to learn which option suits whom. uses features of each user, to learn which option suits whom.

LinUCB models the reward from the features and favors arms it's unsure about. Linear Thompson sampling draws plausible models and plays the best under each draw.

The Decisions & fairness studio brings four jobs together: simulate policies, evaluate a rule on logs, replay learning policies, and audit the results by group. This lesson ties them together.

02

How do you test a learner offline?

Predict

Predict first

Replay steps through logs in which options were assigned uniformly at random. At each row, the policy picks an option. The row only counts if that matches what was logged. With three options, how many rows count?

All of themAbout a thirdHardly any
Reveal

About a third. Out of 1,200 logged rows, each policy matches roughly 400. Because the log was random, those matches are a fair sample of what the policy would have met. So replayReplay evaluationTests a learning policy on uniformly randomized logs, counting only rows where it picks what was logged. works, and it spends a lot of data to do so.

03

Read a replay

In the app
Contextual bandits — replay evaluationRecorded · Python and R agreeRecorded 2026-11-17 · 17 values compared
R

Replayed over 1,200 uniformly logged decisions, LinUCB earned 0.327 per matched decision (398 matches) against 0.280 under the logged random allocation (+17%).

Best policy
LinUCB
Average reward (matched)
0.3266
Logged average reward
0.2800

Plots

Running average reward per matched decisionHow does a value change over time, and how do series compare?
View data
PolicyMatched decisionsAverage reward
LinUCB10
LinUCB50.2000
LinUCB90.1111
LinUCB130.1538
LinUCB170.1176
LinUCB210.1429
LinUCB250.2000
LinUCB290.2414
LinUCB330.2727
LinUCB370.2432
LinUCB410.2439
LinUCB450.2444
LinUCB490.2245
LinUCB530.2264
LinUCB570.2281
LinUCB610.2295
LinUCB650.2615
LinUCB690.2899
LinUCB730.2740
LinUCB770.2727
LinUCB810.2716
LinUCB850.2824
LinUCB890.2921
LinUCB930.3011
LinUCB970.2887
LinUCB1010.2871
LinUCB1050.2857
LinUCB1090.2844
LinUCB1130.2920
LinUCB1170.2991
LinUCB1210.2975
LinUCB1250.2960
LinUCB1290.2946
LinUCB1330.2932
LinUCB1370.2920
LinUCB1410.2979
LinUCB1450.2966
LinUCB1490.2953
LinUCB1530.3007
LinUCB1570.3057
LinUCB1610.3043
LinUCB1650.3030
LinUCB1690.3018
LinUCB1730.3006
LinUCB1770.2938
LinUCB1810.2928
LinUCB1850.2973
LinUCB1890.2910
LinUCB1930.2953
LinUCB1970.3046
LinUCB2020.3020
LinUCB2060.3107
LinUCB2100.3048
LinUCB2140.3037
LinUCB2180.3028
LinUCB2220.3018
LinUCB2260.3142
LinUCB2300.3174
LinUCB2340.3120
LinUCB2380.3067

First 60 of 400 rows.

Replay results

PolicyAverage rewardMatched decisionsLift vs logged
LinUCB0.326639816.7%
Linear Thompson sampling0.28793962.8%
ε-greedy (linear)0.29743906.2%
Uniform random0.30674019.5%
  • Actions: red, green, blue; features: u1, u2, device type (numeric standardized, categories one-hot); rows in order; exploration draws from seed 43.
  • Replay keeps only rows where a policy picks the logged action, so each policy is judged on a different subset.
The exact R script · R R version 4.5.1 (2025-06-13)
# Contextual bandits (replay evaluation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.contextual 1.0.1 · spec c70138057d27530f
# Dataset: o2_uniform (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_replay() / cs_bandit_design(): twins of codesplash.decide.contextual / .ope

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/o2_uniform.parquet", col_select = c("button", "clicked", "u1", "u2", "device type", "propensity")))
n_input <- nrow(df)
df[["button"]] <- factor(df[["button"]], levels = c("red", "green", "blue"))  # stored level order
df[["device type"]] <- factor(df[["device type"]], levels = c("desktop", "mobile"))  # stored level order
df <- df[stats::complete.cases(df[c("button", "clicked", "u1", "u2", "device type", "propensity")]), , 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("button", "clicked", "u1", "u2", "device type", "propensity"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
a_col <- "button"
r_col <- "clicked"
features <- c("u1", "u2", "device type")
p_col <- "propensity" # optional uniform-logging check
chosen <- c(linucb = TRUE, lints = TRUE, epsilon = TRUE,
            random = TRUE)
lab <- cs_bandit_replay_labels()
policies <- names(lab)[chosen[names(lab)]]
if (!length(policies)) stop("Choose at least one policy to replay.")
alpha <- 1
v <- 0.5
epsilon <- 0.1
shuffle <- FALSE
seed <- 42
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as.character(df[[r_col]]) == "true") else as.numeric(df[[r_col]])
is_cat <- vapply(features, function(c) is.factor(df[[c]]), logical(1))
x <- cs_bandit_design(df, features[!is_cat], lapply(stats::setNames(features[is_cat], features[is_cat]), function(c) levels(df[[c]])))
x[, -1] <- cs_bandit_standardize(x[, -1, drop = FALSE]) # policies see standardized features (alpha and v are on that scale)
if (!is.null(p_col)) {
  p <- as.numeric(df[[p_col]])
  if (diff(range(p)) > 1e-9 || abs(p[1] - 1 / length(lv)) > 1e-6) {
    warnings <- c(warnings, sprintf("The logging propensities are not uniform (1/%d): replay estimates are only unbiased under uniform random logging; use off-policy evaluation instead.", length(lv)))
  }
}

# %% Replay
res <- cs_bandit_replay(action, reward, x, lv, policies, alpha = alpha, v = v, epsilon = epsilon, shuffle = shuffle, seed = seed)
pol <- res$policies
n <- res$n
logged <- res$logged
rew <- vapply(policies, function(p) if (pol[[p]]$matched > 0) pol[[p]]$reward else -Inf, numeric(1))
best <- policies[which.max(rew)]
for (p in policies) {
  if (pol[[p]]$matched < 50) warnings <- c(warnings, sprintf("%s matched only %d logged decisions; its estimate is noisy.", lab[[p]], pol[[p]]$matched))
}

# %% Result
summary <- if (logged != 0) {
  sprintf("Replayed over %s uniformly logged decisions, %s earned %.3f per matched decision (%s matches) against %.3f under the logged random allocation (%+.0f%%).",
          format(n, big.mark = ","), lab[[best]], pol[[best]]$reward, format(pol[[best]]$matched, big.mark = ","), logged,
          100 * (pol[[best]]$reward / logged - 1))
} else sprintf("Replayed over %s logged decisions.", format(n, big.mark = ","))
rows <- do.call(rbind, lapply(policies, function(p) {
  data.frame(policy = lab[[p]], reward = pol[[p]]$reward, matched = pol[[p]]$matched, lift = if (logged != 0) pol[[p]]$reward / logged - 1 else NA)
}))
values <- list(logged_reward = logged, n = n, best_policy = best, best_policy_label = lab[[best]], best_reward = pol[[best]]$reward)
for (p in policies) {
  values[[sprintf("reward[%s]", p)]] <- pol[[p]]$reward
  values[[sprintf("matched[%s]", p)]] <- pol[[p]]$matched
  values[[sprintf("curve[%s]", p)]] <- I(pol[[p]]$curve_avg)  # always an array, even with one point (as in Python)
}
curve <- do.call(rbind, lapply(policies, function(p) data.frame(x = pol[[p]]$curve_n, y = pol[[p]]$curve_avg, g = rep(lab[[p]], length(pol[[p]]$curve_n)))))
cs_publish(list(
  method = "bandit.contextual",
  methodVersion = "1.0.1",
  title = "Contextual bandits — replay evaluation",
  engine = cs_engine_info("stats", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "best", label = "Best policy", value = lab[[best]]),
    list(key = "best_reward", label = "Average reward (matched)", value = pol[[best]]$reward),
    list(key = "logged", label = "Logged average reward", value = logged)
  ),
  tables = list(list(
    key = "policies", title = "Replay results",
    columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "reward", label = "Average reward", type = "number"),
                   list(key = "matched", label = "Matched decisions", type = "integer"), list(key = "lift", label = "Lift vs logged", type = "percent")),
    rows = rows
  )),
  warnings = warnings,
  notes = list(
    sprintf("Actions: %s; features: %s (numeric standardized, categories one-hot); %s; exploration draws from seed %s.",
            paste(lv, collapse = ", "), paste(features, collapse = ", "), if (shuffle) "seeded random order" else "rows in order", seed + 1),
    "Replay keeps only rows where a policy picks the logged action, so each policy is judged on a different subset."
  ),
  values = values,
  charts = list(cs_chart("learning", "line", "Running average reward per matched decision", list(
    x = cs_col("Matched decisions", curve$x), y = cs_col("Average reward", curve$y), group = cs_col("Policy", curve$g, levels = unname(lab[policies]))
  )))
))
Python

Replayed over 1,200 uniformly logged decisions, LinUCB earned 0.327 per matched decision (398 matches) against 0.280 under the logged random allocation (+17%).

Best policy
LinUCB
Average reward (matched)
0.3266
Logged average reward
0.2800

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

Replay results

PolicyAverage rewardMatched decisionsLift vs logged
LinUCB0.326639816.7%
Linear Thompson sampling0.28793962.8%
ε-greedy (linear)0.29743906.2%
Uniform random0.30674019.5%
  • Actions: red, green, blue; features: u1, u2, device type (numeric standardized, categories one-hot); rows in order; exploration draws from seed 43.
  • Replay keeps only rows where a policy picks the logged action, so each policy is judged on a different subset.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Contextual bandits (replay evaluation)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.contextual 1.0.1 · spec c70138057d27530f
# Dataset: o2_uniform (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 contextual, ope  # twins of codesplashr::cs_bandit_replay / cs_bandit_design

# %% Data
df = pd.read_parquet("tests/parity/fixtures/o2_uniform.parquet", columns=["button", "clicked", "u1", "u2", "device type", "propensity"])
n_input = len(df)
df["button"] = pd.Categorical(df["button"], categories=["red", "green", "blue"])  # stored level order
df["device type"] = pd.Categorical(df["device type"], categories=["desktop", "mobile"])  # stored level order
df = df.dropna(subset=["button", "clicked", "u1", "u2", "device type", "propensity"])  # listwise deletion over the analysis columns
df["button"] = df["button"].cat.remove_unused_categories()
df["device type"] = df["device type"].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, ["button", "clicked", "u1", "u2", "device type", "propensity"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
a_col, r_col = "button", "clicked"
features = ["u1", "u2", "device type"]
p_col = "propensity"  # optional uniform-logging check
chosen = {"linucb": True, "lints": True, "epsilon": True,
          "random": True}
policies = [p for p in contextual.POLICIES if chosen[p]]
if not policies:
    raise ValueError("Choose at least one policy to replay.")
alpha, v, epsilon = 1, 0.5, 0.1
shuffle = False
seed = 42
levels = [str(x) for x in df[a_col].cat.categories]
action = df[a_col].astype(str).to_numpy()
reward = (df[r_col].astype(str) == "true").astype(float).to_numpy() if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
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)}
x = ope.design(df, numeric, categorical)  # intercept + numerics + one-hot (first level dropped)
x[:, 1:] = contextual.standardize(x[:, 1:])  # policies see standardized features (α and v are on that scale)
if p_col is not None:
    p = df[p_col].to_numpy(dtype=float)
    if np.ptp(p) > 1e-9 or abs(p[0] - 1 / len(levels)) > 1e-6:
        warnings.append(f"The logging propensities are not uniform (1/{len(levels)}): replay estimates are only unbiased under uniform random logging; use off-policy evaluation instead.")

# %% Replay
res = contextual.replay(action, reward, x, levels, policies, alpha=alpha, v=v, epsilon=epsilon, shuffle=shuffle, seed=seed)
pol = res["policies"]
n = res["n"]
logged = res["logged"]
best = max(policies, key=lambda p: (pol[p]["reward"] if pol[p]["matched"] else -np.inf, -policies.index(p)))
for p in policies:
    if pol[p]["matched"] < 50:
        warnings.append(f"{contextual.LABELS[p]} matched only {pol[p]['matched']} logged decisions; its estimate is noisy.")

# %% Result
lab = contextual.LABELS
summary = (
    f"Replayed over {n:,} uniformly logged decisions, {lab[best]} earned {pol[best]['reward']:.3f} per matched decision "
    f"({pol[best]['matched']:,} matches) against {logged:.3f} under the logged random allocation "
    f"({pol[best]['reward'] / logged - 1:+.0%})." if logged else f"Replayed over {n:,} logged decisions."
)
rows = [{"policy": lab[p], "reward": pol[p]["reward"], "matched": pol[p]["matched"], "lift": pol[p]["reward"] / logged - 1 if logged else None} for p in policies]
values = {"logged_reward": logged, "n": n, "best_policy": best, "best_policy_label": lab[best], "best_reward": pol[best]["reward"]}
for p in policies:
    values[f"reward[{p}]"] = pol[p]["reward"]
    values[f"matched[{p}]"] = pol[p]["matched"]
    values[f"curve[{p}]"] = pol[p]["curve_avg"].tolist()
cx, cy, cg = [], [], []
for p in policies:
    cx += pol[p]["curve_n"].tolist()
    cy += pol[p]["curve_avg"].tolist()
    cg += [lab[p]] * len(pol[p]["curve_n"])
cs.publish({
    "method": "bandit.contextual",
    "methodVersion": "1.0.1",
    "title": "Contextual bandits — replay evaluation",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "best", "label": "Best policy", "value": lab[best]},
        {"key": "best_reward", "label": "Average reward (matched)", "value": pol[best]["reward"]},
        {"key": "logged", "label": "Logged average reward", "value": logged},
    ],
    "tables": [{
        "key": "policies", "title": "Replay results",
        "columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "reward", "label": "Average reward", "type": "number"},
                    {"key": "matched", "label": "Matched decisions", "type": "integer"}, {"key": "lift", "label": "Lift vs logged", "type": "percent"}],
        "rows": rows,
    }],
    "warnings": warnings,
    "notes": [
        f"Actions: {', '.join(levels)}; features: {', '.join(features)} (numeric standardized, categories one-hot); "
        f"{'seeded random order' if shuffle else 'rows in order'}; exploration draws from seed {seed + 1}.",
        "Replay keeps only rows where a policy picks the logged action, so each policy is judged on a different subset.",
    ],
    "values": values,
    "charts": [cs.chart("learning", "line", "Running average reward per matched decision", {
        "x": cs.col("Matched decisions", cx), "y": cs.col("Average reward", cy), "group": cs.col("Policy", cg, levels=[lab[p] for p in policies]),
    })],
})

LinUCB earned the most: 0.327 per matched decision, against 0.280 under the logged random allocation.

Now look at the uniform random policy on the same card. It should earn about the logged rate, and it can land noticeably above it. That gap is pure noise, and it tells you how much of the winner's lead to believe.

04

Is the winner stable?

Predict

Predict first

Replay the same logs in a random order, with fewer features and different settings. What happens to the ranking?

The same policy winsA different policy may win
Reveal

A different policy wins: Linear Thompson sampling, at 0.304. With only about 400 matches, each differing by a few percentage points, you can't rank these closely. Run replay more than once before you pick a policy. Rows in time order also matter, if user behavior changes over the log.

05

Check the replay

Checkpoint

Check yourself

Your logs come from a policy that already favored the best-looking options. Can you use replay?

Show the answer

Answer: b

Replay's fairness comes from uniform logging. The Logging propensity role is there as a check on that.

Check yourself

With 1,200 logged rows and 3 uniformly random options, how many matches should a policy expect?

Show the answer

Answer: 400

1,200 / 3 = 400. So replay uses about a third of your data, and its estimates are noisier than the row count suggests.

06

Who pays for exploration?

Reflect

A learning policy tries uncertain options on real people. Those people carry the risk of a worse option, so that later users get a better one.

The burden can fall unevenly. A small group has less data, so the policy stays unsure about it for longer, and explores on it more. And a reward that's measured less well for some users will steer the policy away from them.

If this were a choice about prices, credit or medical care, would you run it? What limits would you put on it?

07

A plain fairness check still applies

In the app

A policy's average reward can rise while one group's falls. So treat a learning policy's decisions like any others:

  1. Split reward and selection rates by group.
  2. Check that exploration isn't concentrated on one group.
  3. Set limits that no policy can cross, as guardrails.

To audit logged decisions, use the Fairness panel in this studio. It needs decisions, outcomes and a group column.

08

Check your understanding

Checkpoint

Check yourself

A personalizing policy raises overall conversion. For one small segment, conversion falls. What should you do?

Show the answer

Answer: b

Averages can hide who pays. The segment's interval may be wide, and that's a reason to look closer, not a reason to ignore it.

Check yourself

When does a contextual bandit add little over a plain one?

Show the answer

Answer: a

Context only helps if the best choice really differs between users. Compare with the plain policy to see whether the extra complexity pays.

09

Try it

In the app

In Decisions & fairness, choose Replay contextual bandits. It needs uniformly randomized logs with context features.

10

Recap

Recap
  • A contextual bandit learns which option suits whom.
  • Replay needs random logs, and it uses about one row in K, for K options.
  • Compare with the random baseline, and repeat before you rank close policies.
  • Audit learning policies by group, since someone carries the cost of exploring.

Concepts in this lesson