Skip to content

DDecisions · bandit.contextual

Contextual bandits (replay evaluation)

Would a learning policy that personalizes by context earn more than the logged random allocation?

Replays LinUCB, linear Thompson sampling and linear ε-greedy policies over uniformly randomized logged decisions (the replay method of Li et al. 2011): at each row a policy picks an action from the context, and when it matches the logged action the reward counts and the policy learns. Gives each policy's online average reward, its lift over random allocation and learning curves; exploration draws come from a shared seeded stream so Python and R agree exactly.

Verified in Python and R Python and R agree to 10 decimals Seeded

A real result

Example “In order”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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.
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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • In ordero2_uniform · action: button · features: u1, u2, device type · propensity: propensity · reward: clicked
  • Shuffled booleano2_uniform · action: button · features: u1, device type · reward: click
  • Two policieso2_uniform · action: button · features: u2 · reward: clicked
  • Degenerate n1o2_uniform · action: button · features: u1, u2, device type · propensity: propensity · reward: clicked

In the guides

Where it sits in the decision guides

  • Reinforcement learning (bandits, RL) · DS & ML Decision Guide · Optimize / decide

What you need

Logged actioncategorical / boolean · 1 column · 2–20 levels
The action taken at random by the logging policy.
Rewardnumeric / boolean · 1 column
The reward observed after each decision (a number, or yes/no for conversions).
Context featuresnumeric / categorical / boolean · 1–50 columns
What the policies see before choosing (numeric features are standardized).
Logging propensity (check)numeric · 0–1 column
Optional: the logging probabilities, to check that logging was uniform (replay needs it).

Choices you make

statistics

LinUCBdefault on

Include LinUCB: picks the arm with the highest optimistic estimate from a linear model of the features.

Linear Thompson samplingdefault on

Include linear Thompson sampling: draws plausible models and plays the best arm under each draw.

ε-greedy (linear)default on

Include ε-greedy: explore a random arm with probability ε, otherwise play the best arm so far.

Uniform random (baseline)default on

Include a uniform random policy as a baseline every learning policy should beat.

LinUCB exploration αdefault 1

How strongly LinUCB favors arms it is unsure about. Higher explores more; lower exploits the current best.

Thompson sampling scale vdefault 0.5

Spread of the posterior draws in linear Thompson sampling. Larger values explore more.

ε (exploration rate)default 0.1

Share of decisions ε-greedy spends exploring a random arm instead of the best one so far.

options

Replay in a random orderdefault off

Off = the rows' order (time order for logs). On = a seeded permutation.

What it reports

logged_reward
Estimates how a new decision policy would have done, using only logs from the current policy.
n
How many independent units the analysis used; it sets precision and power.
best_policy
Code of the policy with the highest average reward per matched decision in the replay, such as linucb or lints.
best_policy_label
Name of the policy with the best result in this run, as the summary names it.
best_reward
Average logged reward on the rows where the best policy would have chosen the action that was actually taken.

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses numpy, scipy, pandas, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Policy scores use small matrix products (numpy vs R BLAS) and Φ⁻¹ (ndtri vs qnorm) that agree to ~1e-15; a different choice would need two arms' scores closer than that.
Python

The exact script CodeSplash ran for example “In order” · 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]),
    })],
})
R

The exact script CodeSplash ran for example “In order” · 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]))
  )))
))

Sources

  • Li, L., Chu, W., Langford, J., & Schapire, R. E. (2010). A contextual-bandit approach to personalized news article recommendation. WWW, 661–670.
  • Li, L., Chu, W., Langford, J., & Wang, X. (2011). Unbiased offline evaluation of contextual-bandit-based news article recommendation algorithms. WSDM, 297–306.
  • Agrawal, S., & Goyal, N. (2013). Thompson sampling for contextual bandits with linear payoffs. ICML, 127–135.

From the CodeSplash method registry · bandit.contextual v1.0.1.