Multi-armed bandits
Shift traffic toward what's working while you learn, measure the cost as regret, and know when a fixed A/B test is still the better tool.
What runs in CodeSplash
- Multi-armed bandit simulation Verified in Python and R
You will be able to
- Define regret, and compute it for a fixed allocation
- Explain how ε-greedy, UCB and Thompson sampling balance exploring and exploiting
- Choose between a bandit and an A/B test
Read first
The cost of a fair test
ReadAn A/B test sends equal traffic to every option until the end, even after one looks better. Users on the weaker option pay for what you learn.
A multi-armed banditMulti-armed banditAllocates traffic while learning, shifting it toward what seems best to lose less during the test. moves traffic toward what's working while it learns. The cost is measured as regretRegretThe reward you missed compared with always using the best option from the start.: the reward you missed compared with always using the best option.
Compute the regret
CheckpointCheck yourself
Three arms convert at 4%, 5% and 6%. A fixed test splits 600 users equally. How many conversions does it lose, on average, against always using the best arm?
Show the answer
Answer: 6
200 users on each arm. Arm 1 loses 0.02 × 200 = 4, arm 2 loses 0.01 × 200 = 2, and arm 3 loses nothing, for a total of 6.
Race them
ExploreEExplorable · The bandit race
How much does it cost to keep testing, and can you shift traffic while you learn?
Which policy will give up the fewest conversions over this many users?
Commit your prediction above to see the result
Make your prediction to see the result.
Narrow the gap between the arms, and see how long the policies take to find the best one. Then widen ε. What does more exploring cost when the gap is large?
Three ways to explore
Read- ε-greedy: play the best arm so far, except for a random arm with probability ε.
- UCB1: play the arm with the highest upper confidence bound, so uncertain arms get a chance.
- Thompson samplingThompson samplingPicks each option with the probability that it is the best one, given what you've seen so far.: play each arm with the probability that it's the best, given what you've seen.
All of them can be tuned. A policy that stops exploring too early can settle on the wrong arm for good.
Who wins?
PredictPredict first
The same simulation runs in three settings: three conversion arms, two close conversion arms, and four noisy arms with delayed feedback. Which policy will lose least?
Reveal
It depends. Softmax (Boltzmann) in the first, Thompson sampling in the second, and UCB1 in the third. No policy wins everywhere. These runs use few replications, too, so check the bands before you declare a winner.
Read the bands
In the appOver 600 decisions and 40 simulated runs, Softmax (Boltzmann) lost the least to always playing the best arm (arm 3): mean cumulative regret 4.41, 80% of runs between 0.08 and 11.77; it played the best arm 50% of the time. A fixed A/B allocation lost 6.04.
- Lowest regret
- Softmax (Boltzmann)
- Mean cumulative regret
- 4.411
- Best arm played
- 50.3%
Policies (cumulative regret at the horizon)
| Policy | Mean regret | SD | 10th pct | 90th pct | Best arm share | Mean total reward |
|---|---|---|---|---|---|---|
| Fixed A/B allocation | 6.040 | 0.1997 | 5.750 | 6.291 | 32.9% | 30.175 |
| ε-greedy | 6.902 | 3.632 | 1.490 | 11.126 | 31.2% | 29.075 |
| Decaying ε-greedy | 4.588 | 3.385 | 0.7840 | 10.236 | 43.2% | 33.025 |
| UCB1 | 5.660 | 0.3693 | 5.187 | 6.075 | 36.3% | 30.750 |
| Thompson sampling | 4.538 | 1.557 | 2.760 | 6.673 | 46.5% | 32.275 |
| Softmax (Boltzmann) | 4.411 | 4.418 | 0.0770 | 11.767 | 50.3% | 31.850 |
- Arms: Arm 1 (0.04), Arm 2 (0.05), Arm 3 (0.06) (conversion); seed 42; regret = best mean − mean of the arm played, summed over decisions.
- Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies.
The exact R script · R R version 4.5.1 (2025-06-13)
# Multi-armed bandit simulation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.simulate 1.0.0 · spec 6493f434cec9832a
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bandit_simulate(): twin of codesplash.decide.bandits (shared Wichmann–Hill stream)
# %% Inputs
arm_kind <- "bernoulli" # bernoulli | gaussian
means <- as.numeric(unlist(c(0.04, 0.05, 0.06))) # true arm means (unknown to the policies)
sd <- 1 # Gaussian arms only
horizon <- as.integer(600)
reps <- as.integer(40)
delay <- as.integer(0)
epsilon <- 0.1
decay_c <- 5
temperature <- 0.01
seed <- 42 # common random numbers: every policy sees the same rewards
chosen <- c(ab = TRUE, epsilon = TRUE, decaying = TRUE,
ucb1 = TRUE, thompson = TRUE, softmax = TRUE)
label <- cs_bandit_policies()
policies <- names(label)[chosen[names(label)]]
if (!length(policies)) stop("Choose at least one policy to simulate.")
if (length(means) < 2) stop("Enter at least two arm means.")
warnings <- list()
# %% Simulate
sim <- cs_bandit_simulate(means, policies, horizon = horizon, reps = reps, seed = seed, arm_kind = arm_kind, sd = sd,
epsilon = epsilon, decay_c = decay_c, temperature = temperature, delay = delay)
res <- sim$policies
k <- length(means)
arm_names <- sprintf("Arm %d (%s)", seq_len(k), format(means, trim = TRUE, drop0trailing = TRUE))
regrets <- vapply(policies, function(p) res[[p]]$regret, numeric(1))
best_policy <- policies[which.min(regrets)]
best_arm <- sim$best_arm
sm <- sort(means, decreasing = TRUE)
if (sm[1] == sm[2]) warnings <- c(warnings, "Two arms share the best mean, so regret only measures time spent on worse arms.")
# %% Result
b <- res[[best_policy]]
summary <- sprintf(
"Over %s decisions and %d simulated runs, %s lost the least to always playing the best arm (arm %d): mean cumulative regret %.2f, 80%% of runs between %.2f and %.2f; it played the best arm %.0f%% of the time.",
format(horizon, big.mark = ","), reps, label[[best_policy]], best_arm, b$regret, b$regret_p10, b$regret_p90, 100 * b$best_share
)
if ("ab" %in% policies && best_policy != "ab") summary <- paste(summary, sprintf("A fixed A/B allocation lost %.2f.", res$ab$regret))
rows <- do.call(rbind, lapply(policies, function(p) {
v <- res[[p]]
data.frame(policy = label[[p]], regret = v$regret, sd = v$regret_sd, p10 = v$regret_p10, p90 = v$regret_p90,
best_share = v$best_share, reward = v$reward)
}))
grid <- sim$grid
band <- do.call(rbind, lapply(policies, function(p) {
data.frame(t = grid, mean = res[[p]]$curve_mean, low = res[[p]]$curve_low, high = res[[p]]$curve_high, policy = label[[p]])
}))
share <- do.call(rbind, lapply(policies, function(p) {
s <- res[[p]]$shares
data.frame(t = rep(grid, each = k), share = as.vector(t(s)), arm = rep(arm_names, times = length(grid)), policy = label[[p]])
}))
values <- list(best_policy = best_policy, best_policy_label = label[[best_policy]], best_regret = b$regret,
best_arm = best_arm, k = k, horizon = horizon, reps = reps)
for (p in policies) {
v <- res[[p]]
values[[sprintf("regret[%s]", p)]] <- v$regret
values[[sprintf("regret_sd[%s]", p)]] <- v$regret_sd
values[[sprintf("regret_p10[%s]", p)]] <- v$regret_p10
values[[sprintf("regret_p90[%s]", p)]] <- v$regret_p90
values[[sprintf("best_share[%s]", p)]] <- v$best_share
values[[sprintf("reward[%s]", p)]] <- v$reward
values[[sprintf("curve[%s]", p)]] <- v$curve_mean
}
cs_publish(list(
method = "bandit.simulate",
methodVersion = "1.0.0",
title = "Multi-armed bandit simulation",
engine = cs_engine_info("stats", "codesplashr"),
n = reps,
summary = summary,
statistics = list(
list(key = "best_policy", label = "Lowest regret", value = label[[best_policy]]),
list(key = "best_regret", label = "Mean cumulative regret", value = b$regret),
list(key = "best_share", label = "Best arm played", value = b$best_share, format = "percent")
),
tables = list(list(
key = "policies", title = "Policies (cumulative regret at the horizon)",
columns = list(
list(key = "policy", label = "Policy", type = "string"), list(key = "regret", label = "Mean regret", type = "number"),
list(key = "sd", label = "SD", type = "number"), list(key = "p10", label = "10th pct", type = "number"),
list(key = "p90", label = "90th pct", type = "number"), list(key = "best_share", label = "Best arm share", type = "percent"),
list(key = "reward", label = "Mean total reward", type = "number")
),
rows = rows
)),
warnings = warnings,
notes = list(
paste0("Arms: ", paste(arm_names, collapse = ", "), " (", if (arm_kind == "bernoulli") "conversion" else sprintf("Gaussian, SD %s", format(sd)),
"); seed ", seed, "; ", if (delay > 0) sprintf("feedback delayed by %d decisions; ", delay) else "",
"regret = best mean − mean of the arm played, summed over decisions."),
"Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies."
),
values = values,
charts = list(
cs_chart("regret", "regret-bands", "Cumulative regret (mean, 10th–90th percentile)", list(
t = cs_col("Decision", band$t), mean = cs_col("Cumulative regret", band$mean), low = cs_col("10th percentile", band$low),
high = cs_col("90th percentile", band$high), policy = cs_col("Policy", band$policy, levels = unname(label[policies]))
)),
cs_chart("shares", "arm-share", "Share of decisions per arm", list(
t = cs_col("Decision", share$t), share = cs_col("Share", share$share), arm = cs_col("Arm", share$arm, levels = arm_names),
policy = cs_col("Policy", share$policy, levels = unname(label[policies]))
))
)
))
Over 600 decisions and 40 simulated runs, Softmax (Boltzmann) lost the least to always playing the best arm (arm 3): mean cumulative regret 4.41, 80% of runs between 0.08 and 11.77; it played the best arm 50% of the time. A fixed A/B allocation lost 6.04.
- Lowest regret
- Softmax (Boltzmann)
- Mean cumulative regret
- 4.411
- Best arm played
- 50.3%
Policies (cumulative regret at the horizon)
| Policy | Mean regret | SD | 10th pct | 90th pct | Best arm share | Mean total reward |
|---|---|---|---|---|---|---|
| Fixed A/B allocation | 6.040 | 0.1997 | 5.750 | 6.291 | 32.9% | 30.175 |
| ε-greedy | 6.902 | 3.632 | 1.490 | 11.126 | 31.2% | 29.075 |
| Decaying ε-greedy | 4.588 | 3.385 | 0.7840 | 10.236 | 43.2% | 33.025 |
| UCB1 | 5.660 | 0.3693 | 5.187 | 6.075 | 36.3% | 30.750 |
| Thompson sampling | 4.538 | 1.557 | 2.760 | 6.673 | 46.5% | 32.275 |
| Softmax (Boltzmann) | 4.411 | 4.418 | 0.0770 | 11.767 | 50.3% | 31.850 |
- Arms: Arm 1 (0.04), Arm 2 (0.05), Arm 3 (0.06) (conversion); seed 42; regret = best mean − mean of the arm played, summed over decisions.
- Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multi-armed bandit simulation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.simulate 1.0.0 · spec 6493f434cec9832a
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import codesplash as cs
from codesplash.decide import bandits # twin of codesplashr::cs_bandit_simulate (shared Wichmann–Hill stream)
# %% Inputs
arm_kind = "bernoulli" # bernoulli | gaussian
means = [float(m) for m in [0.04, 0.05, 0.06]] # true arm means (unknown to the policies)
sd = 1 # Gaussian arms only
horizon = int(600)
reps = int(40)
delay = int(0)
epsilon = 0.1
decay_c = 5
temperature = 0.01
seed = 42 # common random numbers: every policy sees the same rewards
chosen = {
"ab": True, "epsilon": True, "decaying": True,
"ucb1": True, "thompson": True, "softmax": True,
}
policies = [p for p in bandits.POLICIES if chosen[p]]
if not policies:
raise ValueError("Choose at least one policy to simulate.")
if len(means) < 2:
raise ValueError("Enter at least two arm means.")
warnings = []
# %% Simulate
sim = bandits.simulate(means, policies, horizon=horizon, reps=reps, seed=seed, arm_kind=arm_kind, sd=sd, epsilon=epsilon,
decay_c=decay_c, temperature=temperature, delay=delay)
res = sim["policies"]
k = len(means)
arm_names = [f"Arm {i + 1} ({m:g})" for i, m in enumerate(means)]
best_policy = min(policies, key=lambda p: (res[p]["regret"], policies.index(p)))
best_arm = sim["best_arm"] + 1
if sorted(means)[-1] == sorted(means)[-2]:
warnings.append("Two arms share the best mean, so regret only measures time spent on worse arms.")
# %% Result
label = bandits.LABELS
summary = (
f"Over {horizon:,} decisions and {reps} simulated runs, {label[best_policy]} lost the least to always playing the best arm "
f"(arm {best_arm}): mean cumulative regret {res[best_policy]['regret']:.2f}, 80% of runs between {res[best_policy]['regret_p10']:.2f} "
f"and {res[best_policy]['regret_p90']:.2f}; it played the best arm {res[best_policy]['best_share']:.0%} of the time."
)
if "ab" in res and best_policy != "ab":
summary += f" A fixed A/B allocation lost {res['ab']['regret']:.2f}."
rows = [
{"policy": label[p], "regret": res[p]["regret"], "sd": res[p]["regret_sd"], "p10": res[p]["regret_p10"], "p90": res[p]["regret_p90"],
"best_share": res[p]["best_share"], "reward": res[p]["reward"]}
for p in policies
]
grid = sim["grid"]
band_t, band_mean, band_low, band_high, band_policy = [], [], [], [], []
share_t, share_v, share_arm, share_policy = [], [], [], []
for p in policies:
band_t += grid.tolist()
band_mean += res[p]["curve_mean"].tolist()
band_low += res[p]["curve_low"].tolist()
band_high += res[p]["curve_high"].tolist()
band_policy += [label[p]] * len(grid)
for gi, g in enumerate(grid):
for a in range(k):
share_t.append(int(g))
share_v.append(float(res[p]["shares"][gi, a]))
share_arm.append(arm_names[a])
share_policy.append(label[p])
values = {"best_policy": best_policy, "best_policy_label": label[best_policy], "best_regret": res[best_policy]["regret"],
"best_arm": best_arm, "k": k, "horizon": horizon, "reps": reps}
for p in policies:
values[f"regret[{p}]"] = res[p]["regret"]
values[f"regret_sd[{p}]"] = res[p]["regret_sd"]
values[f"regret_p10[{p}]"] = res[p]["regret_p10"]
values[f"regret_p90[{p}]"] = res[p]["regret_p90"]
values[f"best_share[{p}]"] = res[p]["best_share"]
values[f"reward[{p}]"] = res[p]["reward"]
values[f"curve[{p}]"] = res[p]["curve_mean"].tolist()
cs.publish({
"method": "bandit.simulate",
"methodVersion": "1.0.0",
"title": "Multi-armed bandit simulation",
"engine": cs.engine_info("numpy", "scipy"),
"n": reps,
"summary": summary,
"statistics": [
{"key": "best_policy", "label": "Lowest regret", "value": label[best_policy]},
{"key": "best_regret", "label": "Mean cumulative regret", "value": res[best_policy]["regret"]},
{"key": "best_share", "label": "Best arm played", "value": res[best_policy]["best_share"], "format": "percent"},
],
"tables": [{
"key": "policies", "title": "Policies (cumulative regret at the horizon)",
"columns": [
{"key": "policy", "label": "Policy", "type": "string"}, {"key": "regret", "label": "Mean regret", "type": "number"},
{"key": "sd", "label": "SD", "type": "number"}, {"key": "p10", "label": "10th pct", "type": "number"},
{"key": "p90", "label": "90th pct", "type": "number"}, {"key": "best_share", "label": "Best arm share", "type": "percent"},
{"key": "reward", "label": "Mean total reward", "type": "number"},
],
"rows": rows,
}],
"warnings": warnings,
"notes": [
f"Arms: {', '.join(arm_names)} ({'conversion' if arm_kind == 'bernoulli' else f'Gaussian, SD {sd:g}'}); seed {seed}; "
+ (f"feedback delayed by {delay} decisions; " if delay else "")
+ "regret = best mean − mean of the arm played, summed over decisions.",
"Every policy faces the same simulated rewards in each run (common random numbers), so differences are due to the policies.",
],
"values": values,
"charts": [
cs.chart("regret", "regret-bands", "Cumulative regret (mean, 10th–90th percentile)", {
"t": cs.col("Decision", band_t), "mean": cs.col("Cumulative regret", band_mean),
"low": cs.col("10th percentile", band_low), "high": cs.col("90th percentile", band_high),
"policy": cs.col("Policy", band_policy, levels=[label[p] for p in policies]),
}),
cs.chart("shares", "arm-share", "Share of decisions per arm", {
"t": cs.col("Decision", share_t), "share": cs.col("Share", share_v),
"arm": cs.col("Arm", share_arm, levels=arm_names), "policy": cs.col("Policy", share_policy, levels=[label[p] for p in policies]),
}),
],
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Over 600 decisions and 40 simulated runs, the lowest mean regret is 4.41, against about 6 for the fixed split.
Now read the bands, the 10th to 90th percentiles across runs. The fixed split has almost none. Some adaptive policies have very wide ones: they do well on average, and badly when they settle early on a weak arm. Which would you rather defend?
Two close arms
CheckpointCheck yourself
Two arms convert at 10% and 12%. A fixed test splits 800 users equally. What's its expected regret?
Show the answer
Answer: 8
400 users on the weaker arm × 0.02 = 8. The best policy in that simulation lost about 5: a real saving, though not a dramatic one.
A bandit or an A/B test?
ReflectBandits earn more during the test. But a weak arm gets little traffic, so you learn less about it, and estimates of the effect are less precise and can be biased. They also assume that rewards arrive quickly and stay stable.
Think of a decision you make often. Do you need the size of the effect, or only to serve the better option?
Check your understanding
CheckpointCheck yourself · choose all that apply
Which settings suit a bandit better than an A/B test? Select all that apply.
Show the answer
Answer: a, c
Bandits fit when reward during the run is the goal, and feedback is fast. For a precise effect, or for slow outcomes, use a fixed test.
Check yourself
Conversions take a week to arrive. How does that affect a bandit?
Show the answer
Answer: a
A bandit learns only from rewards it has seen. Simulate the delay to see the cost, using the Feedback delay option.
Try it
In the appIn Studios, open Decisions & fairness and choose Compare bandit policies. The Bandit simulation panel needs no data: enter each option's true rate, and compare policies by regret.
The Contextual replay panel adds context features, and learns which option suits which user. The last lesson in this track covers it.
import numpy as np
rng = np.random.default_rng(1)
rates = np.array([0.04, 0.05, 0.06])
wins, losses = np.ones(3), np.ones(3)
regret = 0.0
for _ in range(600):
arm = np.argmax(rng.beta(wins, losses)) # Thompson sampling
reward = rng.random() < rates[arm]
wins[arm] += reward
losses[arm] += 1 - reward
regret += rates.max() - rates[arm]
print(regret)set.seed(1)
rates <- c(0.04, 0.05, 0.06)
wins <- rep(1, 3)
losses <- rep(1, 3)
regret <- 0
for (i in 1:600) {
arm <- which.max(rbeta(3, wins, losses)) # Thompson sampling
reward <- runif(1) < rates[arm]
wins[arm] <- wins[arm] + reward
losses[arm] <- losses[arm] + 1 - reward
regret <- regret + max(rates) - rates[arm]
}
regretThis is one run, using each language's own random generator. CodeSplash averages over many runs on a shared stream.
Recap
Recap- Regret is the reward you missed compared with always playing the best arm.
- Bandits lose less during a run, and no policy wins everywhere.
- Read the bands as well as the mean.
- Use an A/B test when you need the size of the effect.
Concepts in this lesson