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.
What runs in CodeSplash
- Contextual bandits (replay evaluation) Verified in Python and R
- Off-policy evaluation of a decision policy Verified in Python and R
- Fairness assessment of decisions across groups Verified in Python and R
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
From best overall to best for whom
ReadA 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.
How do you test a learner offline?
PredictPredict 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?
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.
Read a replay
In the appReplayed 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
View data
| Policy | Matched decisions | Average reward |
|---|---|---|
| LinUCB | 1 | 0 |
| LinUCB | 5 | 0.2000 |
| LinUCB | 9 | 0.1111 |
| LinUCB | 13 | 0.1538 |
| LinUCB | 17 | 0.1176 |
| LinUCB | 21 | 0.1429 |
| LinUCB | 25 | 0.2000 |
| LinUCB | 29 | 0.2414 |
| LinUCB | 33 | 0.2727 |
| LinUCB | 37 | 0.2432 |
| LinUCB | 41 | 0.2439 |
| LinUCB | 45 | 0.2444 |
| LinUCB | 49 | 0.2245 |
| LinUCB | 53 | 0.2264 |
| LinUCB | 57 | 0.2281 |
| LinUCB | 61 | 0.2295 |
| LinUCB | 65 | 0.2615 |
| LinUCB | 69 | 0.2899 |
| LinUCB | 73 | 0.2740 |
| LinUCB | 77 | 0.2727 |
| LinUCB | 81 | 0.2716 |
| LinUCB | 85 | 0.2824 |
| LinUCB | 89 | 0.2921 |
| LinUCB | 93 | 0.3011 |
| LinUCB | 97 | 0.2887 |
| LinUCB | 101 | 0.2871 |
| LinUCB | 105 | 0.2857 |
| LinUCB | 109 | 0.2844 |
| LinUCB | 113 | 0.2920 |
| LinUCB | 117 | 0.2991 |
| LinUCB | 121 | 0.2975 |
| LinUCB | 125 | 0.2960 |
| LinUCB | 129 | 0.2946 |
| LinUCB | 133 | 0.2932 |
| LinUCB | 137 | 0.2920 |
| LinUCB | 141 | 0.2979 |
| LinUCB | 145 | 0.2966 |
| LinUCB | 149 | 0.2953 |
| LinUCB | 153 | 0.3007 |
| LinUCB | 157 | 0.3057 |
| LinUCB | 161 | 0.3043 |
| LinUCB | 165 | 0.3030 |
| LinUCB | 169 | 0.3018 |
| LinUCB | 173 | 0.3006 |
| LinUCB | 177 | 0.2938 |
| LinUCB | 181 | 0.2928 |
| LinUCB | 185 | 0.2973 |
| LinUCB | 189 | 0.2910 |
| LinUCB | 193 | 0.2953 |
| LinUCB | 197 | 0.3046 |
| LinUCB | 202 | 0.3020 |
| LinUCB | 206 | 0.3107 |
| LinUCB | 210 | 0.3048 |
| LinUCB | 214 | 0.3037 |
| LinUCB | 218 | 0.3028 |
| LinUCB | 222 | 0.3018 |
| LinUCB | 226 | 0.3142 |
| LinUCB | 230 | 0.3174 |
| LinUCB | 234 | 0.3120 |
| LinUCB | 238 | 0.3067 |
First 60 of 400 rows.
Replay results
| Policy | Average reward | Matched decisions | Lift vs logged |
|---|---|---|---|
| LinUCB | 0.3266 | 398 | 16.7% |
| Linear Thompson sampling | 0.2879 | 396 | 2.8% |
| ε-greedy (linear) | 0.2974 | 390 | 6.2% |
| Uniform random | 0.3067 | 401 | 9.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]))
)))
))
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
| Policy | Average reward | Matched decisions | Lift vs logged |
|---|---|---|---|
| LinUCB | 0.3266 | 398 | 16.7% |
| Linear Thompson sampling | 0.2879 | 396 | 2.8% |
| ε-greedy (linear) | 0.2974 | 390 | 6.2% |
| Uniform random | 0.3067 | 401 | 9.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.
Is the winner stable?
PredictPredict first
Replay the same logs in a random order, with fewer features and different settings. What happens to the ranking?
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.
Check the replay
CheckpointCheck 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.
Who pays for exploration?
ReflectA 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?
A plain fairness check still applies
In the appA policy's average reward can rise while one group's falls. So treat a learning policy's decisions like any others:
- Split reward and selection rates by group.
- Check that exploration isn't concentrated on one group.
- 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.
Check your understanding
CheckpointCheck 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.
Try it
In the appIn Decisions & fairness, choose Replay contextual bandits. It needs uniformly randomized logs with context features.
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