Build a Bandit-Based Recommendation System for Online Exploration
recommendation-systems ranking model-evaluation classical-ml View full code for this problem
ML Problem & Solution
Bandits for Online Exploration
A policy that picks what to show also decides what you will be able to learn
The homepage has 40 candidate rails and room for one above the fold. Editorial picks the winner. Last quarter someone proposed replacing editorial with an A/B test, which ran for three weeks on a 40-way split, returned a confidence interval on each rail wide enough to contain zero, and cost an estimated 4% of homepage clicks for the duration because 39 of the 40 traffic slices were showing something worse than the incumbent the whole time. The test then shipped the point-estimate winner, which regressed in the following month, because the arm that won a three-week test on 2.5% of traffic won it by noise.
This is the structural problem with a fixed split, and it has nothing to do with statistics being hard. An A/B test commits to a traffic allocation before it has any data and then refuses to update it, so the cost of the experiment is fixed in advance at (K - 1) / K of traffic receiving a suboptimal treatment, and the information gained is spread evenly across arms including the arms that revealed themselves to be terrible in the first hour. Post 27 ended on the observation that clicks on what you served cannot measure what you failed to retrieve. The same loop closes here and tighter: the policy that decides what to show decides what gets clicked, which decides what the next version of the policy learns, so there is no held-out slice of a counterfactual anywhere.
The naive fix is to watch the dashboard and kill the losers early, which is the right instinct and is also a bandit with an unspecified algorithm, an unlogged policy and no propensities. It works, in the sense that it beats the fixed split, and it destroys the ability to evaluate anything afterwards: a human who reallocated traffic on a hunch on Tuesday has produced a log whose action probabilities are unknown and therefore unusable for every estimator in this post.
Think of the fixed split as a survey with a fixed sample size per option, and a bandit as a survey that reallocates interviewers toward the questions still in doubt. The second one answers the question you asked faster. It also comes back with almost nothing to say about the options it stopped asking about, and that is a real cost and not a technicality.
Formally: at each round t a context x_t arrives, we choose an arm a_t from K candidates, and observe a binary reward r_t. Minimise cumulative pseudo-regret, sum_t (p*(x_t) - p(a_t, x_t)), over a horizon T, subject to the reward arriving D rounds after the decision, and subject to the log remaining usable for off-policy evaluation afterwards.
Framing the Problem
The ML problem type is sequential decision-making under partial feedback, and the “partial” is the whole thing: we observe the reward of the arm we chose and never the rewards of the 39 we did not. That single asymmetry separates this from every supervised problem in posts 21 through 27, where the label for every candidate was available in the log.
The target is a binary click on the rail in the above-the-fold slot. The reward is defined per impression rather than per session, which is a decision with a cost noted in the pitfalls section: it assumes rounds are independent, and they are not, because the rounds are the same people repeatedly.
Constraints, in the order they bind:
- The reward arrives between 4 and 90 minutes after the impression, which at homepage volume is 35 to 800 rounds of delay.
- 25% of the rails have quality that drifts over weeks, because the content behind them turns over.
- The log must remain usable for off-policy evaluation, which means every action’s probability must be recorded at decision time. Reconstructing it later is not possible.
- Exposure floors: no rail may fall below 0.5% of traffic, which is a product commitment and also, conveniently, what keeps the log evaluable.
- The reward model is misspecified. Context is 12 features and the true response is not linear in them.
The success metric is cumulative pseudo-regret, and the guardrail metrics are the across-seed spread of that regret and the number of arms left with too little data to evaluate.
Pseudo-regret rather than realised regret, and the reason is a ratio you can compute before writing any code. Pseudo-regret is `sum_t (p*(x_t) - p(a_t, x_t))`, the difference in EXPECTED reward between the best arm and the chosen one, which isolates the decision from the coin flip. Realised regret is the difference in actual clicks and is dominated by Bernoulli noise: at the companion codebase's measured mean CTR of 0.0505 the per-round noise standard deviation is 0.2189, and a good policy's per-round pseudo-regret is about 0.05, so the noise is four times the signal every single round. A realised-regret curve is a random walk with a faint trend, and most bandit comparisons that end in an argument are arguments about one. The second metric, which is not optional, is the ACROSS-SEED SPREAD: a bandit run is one sample from a very wide distribution, and in the companion codebase the across-seed standard deviation of several policies exceeds the gap between them. Any bandit table built from a single run reports which policy got lucky.
Out of scope: slate and ranked-list bandits, where the action is an ordered set and the reward attribution across positions is its own problem; adversarial bandits, where the reward is chosen by an opponent rather than drawn from a distribution; and the reinforcement-learning case where the action changes the state, which this does not, since each round’s context arrives independently of what we did last round.
Everything a bandit post concludes is downstream of one number that is almost never reported: the gap between the best arm and the field. The companion codebase's first calibration had a mean CTR of 0.1188 with a best-arm mean of 0.6754 and a mean gap of 0.5566, which are plausible-looking numbers and are a slot machine with one jammed lever rather than a recommender. In that world LinUCB scored 2336.35 against epsilon-greedy's 5353.74, so contextual beat non-contextual by 2.3x and the central question answered itself. Recalibrated to a mean CTR of 0.0505 and a gap of 0.0766, which is the regime a real homepage rail lives in, the SAME TWO POLICIES scored 837.78 and 718.11 and the ordering reversed. Nothing about either algorithm changed. When reading any published bandit comparison, find the base rate and the gap first; if they are not stated, the ranking in the table is not transferable to your problem, and if the base rate is near 0.5 it is not a recommender result at all.
Data and Features
There is no dataset, and that sentence is the methodological content of this section rather than an admission. The log is generated by the policy, so “the data” is a function of the thing being evaluated, and the companion codebase therefore ships an explicit simulator whose ground truth is readable so that exact regret is computable.
The environment has three properties that are deliberate, because each one breaks a different algorithm:
# The true click probability of every arm. The ONLY place ground truth exists.
import numpy as np
def expected_reward(self, x: np.ndarray, t: int) -> np.ndarray:
"""Three deliberate properties: misspecification, drift, and a low base rate."""
lin = self.theta @ x
# A squared projection: the mildest interesting misspecification, because
# it is monotone in |x . w| so the ranking is distorted rather than
# scrambled. That is the regime where a linear model is wrong and does
# not look wrong.
nonlin = (self.nonlinear_w @ x) ** 2 - 1.0
drift_term = self.drift * (t / max(self.n_rounds, 1))
logit = (self.base
+ np.sqrt(1.0 - self.nonlinear_share) * lin
+ np.sqrt(self.nonlinear_share) * nonlin
+ drift_term)
return 1.0 / (1.0 + np.exp(-logit))
Working in logit space rather than clipping probabilities is not fastidiousness. Clipping a probability at 0 or 1 makes several arms exactly optimal, which makes regret look better than it is for reasons that have nothing to do with the policy.
The measured calibration, which the default run prints so it is visible rather than implicit:
| Quantity | Value | Why it matters |
|---|---|---|
| Mean true CTR | 0.0505 | The regime a real rail lives in, not 0.5 |
| Best-arm mean CTR | 0.1271 | Only 2.5x the mean, so the problem is genuinely hard |
| Gap, best minus average arm | 0.0766 | The hidden variable in every benchmark |
| Gap, best minus second-best | 0.0256 | What the policy actually has to resolve |
| Arms optimal for some context | 35 of 40 | The context genuinely matters |
| Single most-often-optimal arm | best 18.5% of the time | The ceiling on any non-contextual policy |
| Bernoulli noise sd per round | 0.2189 | Four times the per-round signal |
| Non-linear share of the signal | 35% | LinUCB’s regret bound does not apply |
The 18.5% row is the one to keep. It is the best optimal-action rate a policy that ignores context can achieve, so it is the bar the contextual policies have to clear to justify their 480 parameters.
Build the simulator even when you have a real log, and build it so its ground truth is readable. This sounds like the opposite of good practice and is the only way to measure the thing that actually decides whether this project succeeds, which is HOW WRONG YOUR EVALUATION IS. Exact regret is computable against a known environment and is not computable anywhere else, ever, so the errors in the off-policy table later in this post, which run from +4.8% to +96.0%, are numbers no amount of production data can produce: in production you have an estimate and no truth to compare it against, which is precisely the situation in which an estimator that is off by 96% looks exactly like one that is off by 5%. The second reason is cheaper and more immediate: the simulator is where you discover that your estimator implementation has a sign error or that your propensity logging drops the delayed rows, because it is the only place a known answer exists. Treat the simulator as a test harness for the evaluation code rather than as a substitute for data, and keep the generative constants in config so the calibration is visible, which the previous callout explains the cost of getting wrong.
Not recording the action probability at decision time. This is the one mistake in this post that cannot be fixed afterwards, and it is the reason the propensity is part of the policy interface in the companion codebase rather than something computed later. Every estimator in "Evaluation and Metrics" needs `mu(a | x)`, the probability the logging policy assigned to the action it took, and that number exists only in the instant the decision was made: an epsilon-greedy policy's propensity depends on which arm was its argmax at that moment, which depends on its state, which depended on the rewards it had received by then, several of which were still in flight. Reconstructing it from a replayed log requires reproducing the policy's exact state at every round including the delay buffer, and if any part of the pipeline was nondeterministic it is not recoverable at all. The practical consequence measured in the companion codebase: a deterministic target policy evaluated against an epsilon-greedy logger at epsilon 0.15 has an EFFECTIVE SAMPLE SIZE OF 39 out of 12,000 logged rounds, with a maximum importance weight of 266.7. That number is terrible and it is also the single most useful diagnostic available, and you can only compute it if the propensity was written down. A team that logs the chosen action but not its probability has a log that can train a model and cannot evaluate a policy.
The Naive Baseline
Three baselines, and the second one is the instructive failure.
# Greedy and epsilon-greedy. The second is the most deployed bandit in the world.
import numpy as np
class Greedy:
"""Pure exploitation on the empirical mean.
Its failure is specific and worth seeing: it is not that greedy explores
too little on average, it is that greedy LOCKS. One unlucky early
sequence on the true best arm and that arm is never pulled again.
"""
def __init__(self, n_arms: int) -> None:
self.counts = np.zeros(n_arms)
self.sums = np.zeros(n_arms)
def means(self) -> np.ndarray:
# Unseen arms score 1.0, which forces one pull of each. Scoring them
# 0.0 instead makes greedy pull arm 0 forever, which is a real bug
# and reads as "greedy is much worse than expected".
return np.where(self.counts > 0, self.sums / np.maximum(self.counts, 1), 1.0)
def select(self, x: np.ndarray, t: int) -> int:
return int(np.argmax(self.means()))
def update(self, arm: int, x: np.ndarray, reward: float) -> None:
self.counts[arm] += 1
self.sums[arm] += reward
class EpsilonGreedy(Greedy):
"""Explore uniformly with probability eps, else exploit.
Fixed eps has LINEAR regret by construction, because it keeps paying
eps * gap forever. It is still the most deployed bandit anywhere,
because at a finite horizon the constant matters and the asymptote does
not.
"""
def __init__(self, n_arms: int, eps: float = 0.1,
decay_c: float | None = None, seed: int = 0) -> None:
super().__init__(n_arms)
self.eps0, self.decay_c = eps, decay_c
self.rng = np.random.default_rng(seed)
def eps(self, t: int) -> float:
return self.eps0 if self.decay_c is None else min(1.0, self.decay_c / max(t, 1))
def select(self, x: np.ndarray, t: int) -> int:
if self.rng.uniform() < self.eps(t):
return int(self.rng.integers(len(self.counts)))
return int(np.argmax(self.means()))
def propensity(self, x: np.ndarray, t: int, arm: int) -> float:
"""Recorded at decision time. See the pitfall above."""
e, n = self.eps(t), len(self.counts)
return e / n + (1.0 - e) * (1.0 if arm == int(np.argmax(self.means())) else 0.0)
| Baseline | Regret | sd | Range over 12 seeds | Optimal-action rate | Arms under 30 pulls |
|---|---|---|---|---|---|
| Random, no learning | 1153.67 | 198.16 | 867.0 to 1582.4 | 0.0248 | 0.0 |
| Greedy | 1067.12 | 188.31 | 768.5 to 1393.0 | 0.0218 | 38.2 |
| Epsilon-greedy, 0.10 | 689.18 | 163.85 | 360.6 to 909.1 | 0.2019 | 9.2 |
| Epsilon-greedy, decaying | 682.78 | 221.29 | 255.5 to 1158.6 | 0.1905 | 33.9 |
Greedy at 1067.12 is 92.5% of no-learning-at-all, and its optimal-action rate of 0.0218 is below uniform random’s 0.0248. It is not merely bad, it is anti-informative: it commits to an arm on the basis of a handful of Bernoulli draws at a 5% rate and then stops collecting the evidence that would change its mind. The coverage column is the same story from the other side, with 38.2 of 40 arms left under 30 pulls and the top arm taking 99.3% of traffic.
Epsilon-greedy at 0.10 is the number everything else has to beat and it is a serious number: 689.18 against random’s 1153.67, 59.7% of the no-learning regret, and 459 extra clicks over the horizon. It costs one line of code, has no model, no matrix inverse and no posterior.
Read the `sd` column before the `regret` column, always, and the decaying-epsilon row is why. It has the best mean of the four at 682.78 and the worst spread of anything in this post, with a standard deviation of 221.29 and a range from 255.5 to 1158.6. Its best seed is the best result on the page and its worst seed is barely better than greedy. The policy with the better asymptotic guarantee has, at the horizon that matters, a realised outcome that is a lottery. This matters beyond table-reading hygiene because of how the decision actually gets made: somebody runs each candidate once, puts the numbers in a document, and the document is then true for a year. With these spreads, a single run of decaying epsilon-greedy returns anything from 255 to 1159, which is to say it returns the whole range of conclusions available. Twelve seeds is the minimum here and it is not enough for the pairs that are close, which the next section quantifies.
The Solution
Four policies, in two families, and the measured result is that the family matters less than one constant.
Optimism: UCB1 and LinUCB
The analogy is a bureaucrat who assumes the best about every option they have not investigated, so the only way to stop them championing an option is to investigate it and be disappointed. Score each arm at the upper end of its confidence interval and the arms you have ignored float to the top automatically, which means exploration is a consequence of the scoring rule rather than a separate random branch.
# LinUCB: one ridge regression per arm, plus a confidence ellipsoid.
import numpy as np
class LinUCB:
"""`alpha` is the ellipsoid width in posterior standard deviations.
The inverse is maintained INCREMENTALLY by Sherman-Morrison rather than
recomputed. Recomputing is O(d^3) per arm per round, and the usual fix
once a team notices the cost is to update every N rounds, which silently
turns the policy into a batched one whose intervals are stale by up to N
rounds.
"""
def __init__(self, n_arms: int, n_features: int, alpha: float = 0.02,
lam: float = 1.0) -> None:
self.A_inv = np.array([np.eye(n_features) / lam for _ in range(n_arms)])
self.b = np.zeros((n_arms, n_features))
self.alpha, self.d = alpha, n_features
def select(self, x: np.ndarray, t: int) -> int:
mean = np.einsum("aij,aj,i->a", self.A_inv, self.b, x)
var = np.einsum("i,aij,j->a", x, self.A_inv, x)
return int(np.argmax(mean + self.alpha * np.sqrt(np.maximum(var, 0.0))))
def update(self, arm: int, x: np.ndarray, reward: float) -> None:
Ai = self.A_inv[arm]
Aix = Ai @ x
# (A + x x^T)^-1 = A^-1 - (A^-1 x)(x^T A^-1) / (1 + x^T A^-1 x)
self.A_inv[arm] = Ai - np.outer(Aix, Aix) / (1.0 + float(x @ Aix))
self.b[arm] += reward * x
Posterior sampling: Thompson and LinTS
The analogy is a committee member who, each time they are asked, states a belief drawn at random from what the evidence allows, so an option the committee is uncertain about gets championed sometimes and an option it is sure is bad never does. One line of exploration logic and no exploration parameter in the non-contextual case.
# Linear Thompson sampling, with the implementation detail that matters most.
import numpy as np
class LinTS:
"""The textbook form draws a full parameter vector per arm per round,
theta_a ~ N(mu_a, v^2 A_a^-1), which needs a d-by-d Cholesky factor every
time. But the policy only uses the draw through `theta_a . x`, and a
linear functional of a Gaussian has a closed-form marginal:
theta_a . x ~ N( mu_a . x , v^2 * x^T A_a^-1 x )
So one normal draw per arm reproduces the identical distribution. Not an
approximation. Measured: the companion codebase's default run went from
79.2s to 27.6s, and it removed a real failure mode, since A_inv
accumulates error through repeated Sherman-Morrison updates and can lose
positive-definiteness, at which point `cholesky` raises and the usual
jitter fix silently changes the policy.
"""
def __init__(self, n_arms: int, n_features: int, v: float = 0.03,
lam: float = 1.0, seed: int = 0) -> None:
self.A_inv = np.array([np.eye(n_features) / lam for _ in range(n_arms)])
self.b = np.zeros((n_arms, n_features))
self.v, self.n_arms = v, n_arms
self.rng = np.random.default_rng(seed)
def select(self, x: np.ndarray, t: int) -> int:
mean = np.einsum("aij,aj,i->a", self.A_inv, self.b, x)
var = np.einsum("i,aij,j->a", x, self.A_inv, x)
sd = self.v * np.sqrt(np.maximum(var, 0.0))
return int(np.argmax(mean + sd * self.rng.normal(size=self.n_arms)))
The hyperparameter that matters more than the algorithm
The theory prescribes c = 1 for UCB1’s bonus of c * sqrt(2 ln t / n_a) and v = 1 for linear Thompson sampling’s posterior scale. Both are the worst value measured.
| Parameter | 0.00 | 0.01 to 0.03 | best | theory’s 1.00 |
|---|---|---|---|---|
UCB1 c |
1119.44 | 875.08 at 0.03 | 600.09 at 0.10 | 1084.28 |
LinUCB alpha |
870.54 | 625.04 at 0.02 | 625.04 at 0.02 | 918.76 |
LinTS v |
- | 657.13 at 0.01 | 657.13 at 0.01 | 1100.53 |
Epsilon-greedy eps |
- | - | 718.11 at 0.10 | - |
Part of this has a clean explanation that is checkable. Both bounds are worst-case over all reward distributions on [0, 1], which assumes a variance of 0.25; at the measured mean CTR of 0.0505 the real variance is 0.048, so the prescribed exploration is sqrt(0.25 / 0.048) or about 2.3 times wider than the data warrants. That factor is real and nowhere near large enough to explain the gap, which is 10x for UCB1 and 50x for LinTS. The remainder is the horizon: a log t bonus is calibrated for t far beyond 12,000, and with 40 arms the policy has around 300 pulls per arm, so most of the optimism is still unretired when the horizon ends. We can account for 2.3x of it and not the rest, and the rule that survives is to sweep it.
The exploration constant is not a tuning detail here, it is the result. At the commonly cited `alpha = 0.45` LinUCB scores 837.78 and LOSES to epsilon-greedy's 718.11; at the swept 0.02 it scores 631.37 and wins. The entire contextual-versus-non-contextual conclusion, which is the question the project exists to answer, was downstream of one constant copied from a paper. There is a second-order lesson that cost us more time than the first: our original sweep grids were `[0.10, 0.30, 0.60, 1.00, 2.00]` and `[0.10, 0.25, 0.45, 1.00, 2.00]`, and ALL FOUR SWEEPS SELECTED THEIR LOWEST GRID POINT. A sweep whose argmin is its first point has not found an optimum, it has found a wall, and every comparison downstream of it is one tuned policy against three untuned ones. Extending the grids downward moved LinUCB's optimum from 0.10 to 0.02 and revealed that the curve is genuinely interior, since 0.00 scores 870.54. Check that your grid brackets the optimum before reading anything else off a sweep.
Evaluation and Metrics
Two evaluations, and the second is the one with no good answer.
Online: regret across seeds
# Pseudo-regret, realised regret, and the delay buffer, in one driver loop.
from collections import deque
import numpy as np
def simulate(env, policy, n_rounds: int, delay: int = 0, seed: int = 0):
"""One loop for every policy, so the delay, logging and accounting are
identical across them and cannot explain a difference between two."""
rng = np.random.default_rng(seed)
env.rng = rng
pseudo = np.zeros(n_rounds)
realised = np.zeros(n_rounds)
pending: deque = deque()
for t in range(1, n_rounds + 1):
x = env.context()
probs = env.expected_reward(x, t)
best_p = float(probs.max())
arm = policy.select(x, t)
reward = env.pull(arm, x, t)
pseudo[t - 1] = best_p - float(probs[arm])
realised[t - 1] = best_p - reward
pending.append((arm, x, float(reward)))
if len(pending) > delay:
policy.update(*pending.popleft())
while pending: # drain, or `delay` observations are lost
policy.update(*pending.popleft())
return np.cumsum(pseudo), np.cumsum(realised)
| Policy | Regret | sd | sem | Range over seeds | Optimal-action rate | Clicks |
|---|---|---|---|---|---|---|
| Random | 1153.67 | 198.16 | 57.20 | 867.0 to 1582.4 | 0.0248 | 646 |
| Greedy | 1067.12 | 188.31 | 54.36 | 768.5 to 1393.0 | 0.0218 | 730 |
| Epsilon-greedy 0.10 | 689.18 | 163.85 | 47.30 | 360.6 to 909.1 | 0.2019 | 1106 |
| Epsilon-greedy decay | 682.78 | 221.29 | 63.88 | 255.5 to 1158.6 | 0.1905 | 1116 |
| UCB1 c=0.10 | 589.48 | 152.91 | 44.14 | 266.7 to 771.2 | 0.2563 | 1204 |
| Thompson beta(1,12) | 744.11 | 129.61 | 37.41 | 458.6 to 860.7 | 0.1851 | 1054 |
| LinUCB alpha=0.02 | 631.37 | 67.58 | 19.51 | 533.4 to 764.5 | 0.2198 | 1162 |
| LinTS v=0.03 | 641.40 | 81.09 | 23.41 | 482.5 to 763.3 | 0.2214 | 1160 |
UCB1 has the lowest mean and it is not meaningfully better than LinUCB. The gap is 41.89 against standard errors of 44.14 and 19.51, so the pooled standard error of the difference is about 48.3 and the gap is 0.87 of it. On twelve seeds those two are indistinguishable, and “UCB1 wins” is not a finding this table supports.
What the table does support is a statement about spread. LinUCB’s across-seed standard deviation is 67.58 against UCB1’s 152.91, less than half, and its range is 533.4 to 764.5 against UCB1’s 266.7 to 771.2. UCB1’s upside is much better and its downside is slightly worse. For a homepage that has to work every week rather than on average, the decisive column points the opposite way from the mean.
The crossover: when does context pay for itself?
This is the question the project exists to answer and it is a sample-size question rather than a theoretical one. A contextual policy here fits 40 arms times 12 features, or 480 coefficients. A non-contextual one fits 40. At a mean CTR of 0.0505, a horizon of T rounds yields about 0.0505 T clicks, and the clicks are what carry information about a coefficient, so T has to be a healthy multiple of 480 / 0.0505 = 9,505 before the contextual model has anything to work with.
| Regret per round | T=3,000 | T=12,000 | T=40,000 | T=120,000 |
|---|---|---|---|---|
| Epsilon-greedy 0.10 | 0.06354 | 0.05984 | 0.05160 | 0.04918 |
| Thompson beta | 0.07868 | 0.06286 | 0.04871 | 0.04584 |
| LinUCB alpha=0.02 | 0.07634 | 0.05209 | 0.04157 | 0.03380 |
| LinUCB over epsilon-greedy | 1.201 | 0.870 | 0.806 | 0.687 |
The crossover sits between 3,000 and 12,000 rounds, which brackets the 9,505 estimate. At 3,000 rounds the contextual policy is 20% worse; at 120,000 it is 31% better; and nothing about either algorithm changes across those rows.
Off-policy: evaluating without deploying
In production you have a log from the policy you shipped and a candidate you want to assess without shipping it. The identity every estimator rests on is V(pi) = E_x[ sum_a pi(a|x) r(x,a) ], and the log contains only r(x, a_logged).
# IPS and doubly robust. The clip is the bias-variance dial.
def ips(log: list, target_propensity, clip: float | None = None) -> dict:
"""Unbiased given support, and the variance is the problem, not the bias."""
num, n, weights = 0.0, 0, []
for row in log:
mu = row["propensity"]
if mu <= 0:
continue
w = target_propensity(row["x"], row["t"], row["arm"]) / mu
if clip is not None:
w = min(w, clip)
weights.append(w)
num += w * row["reward"]
n += 1
w = np.array(weights)
return {"estimate": num / max(n, 1),
"max_weight": float(w.max()),
# Kish's effective sample size. Report this or do not report the estimate.
"ess": float(w.sum() ** 2 / max((w ** 2).sum(), 1e-12))}
def doubly_robust(log: list, model, target_propensity, n_arms: int) -> dict:
"""Direct method plus an importance-weighted correction of its own error.
Unbiased if EITHER the propensities or the reward model is right, which
is the property that makes it the default recommendation and which the
measurement below does not bear out.
"""
total = 0.0
for row in log:
x, a_log, r, mu = row["x"], row["arm"], row["reward"], row["propensity"]
if mu <= 0:
continue
q = model.predict(x)
probs = np.array([target_propensity(x, row["t"], a) for a in range(n_arms)])
total += float(probs @ q) + (probs[a_log] / mu) * (r - q[a_log])
return {"estimate": total / max(len(log), 1)}
Because the environment’s ground truth is knowable, the error of each estimator is itself measurable. True value of the target policy: 0.0819 clicks per round.
| Estimator | Epsilon-greedy log (0.15) | Error | Uniform log | Error | Effective n |
|---|---|---|---|---|---|
| IPS | 0.1352 | +65.0% | 0.0967 | +18.0% | 39 / 278 |
| IPS clipped at 20 | 0.0119 | -85.5% | 0.0483 | -41.0% | 63 / 278 |
| SNIPS | 0.1606 | +96.0% | 0.1043 | +27.3% | 39 / 278 |
| Direct method | 0.0614 | -25.0% | 0.1062 | +29.6% | - |
| Doubly robust | 0.1479 | +80.5% | 0.1040 | +26.9% | 39 / 278 |
| Replay | 0.0858 | +4.8% | 0.0747 | -8.8% | 699 / 281 rounds kept |
Three things in that table, and all three contradict the textbook.
The crudest estimator is five to twenty times more accurate than the sophisticated ones. Replay walks the log, accepts the rounds where the target policy would have chosen the logged action, and discards the rest. It retains 5.83% and 2.34% of the log respectively, it needs no propensity arithmetic, and it is within 8.8% on both logs while everything else is off by 18% to 96%.
Clipping made every estimate dramatically worse, in the direction that looks like success. Clipped IPS gives 0.0119 against a true 0.0819, an error of -85.5%, against unclipped IPS’s +65.0%. The variance fell and the answer landed near the logger’s own CTR of 0.0609, which is a plausible-looking number and is the wrong quantity. Clipping bias is always downward and always worst for the actions the target likes and the logger avoided, which are the only actions the evaluation was ever about.
Doubly robust was not better than plain IPS, +80.5% against +65.0% on the epsilon-greedy log. Its guarantee is that it is unbiased if either component is right, and here neither is: the propensities have an effective sample size of 39, and the reward model’s worst arm was fitted on 36 observations for 12 coefficients.
The direct method's reward model is fitted on the actions the LOGGER chose, so it is accurate for arms the logger pulled often and extrapolating for arms it avoided, which are exactly the arms a better target policy wants to pull. A direct-method estimate is therefore most confident precisely where it is least trustworthy, and that property is inherited by every doubly robust estimator built on top of one. The diagnostic nobody computes is the per-arm fit size, which the companion codebase prints: under the epsilon-greedy logger the worst arm has 36 observations for 12 coefficients and the direct method comes in at -25.0%; under the uniform logger the worst arm has 268 and it comes in at +29.6%, which is worse in magnitude and is a reminder that more data per arm fixes the variance and not the misspecification, since the environment is 35% non-linear and the model is linear. The practical reading is that the direct method's error is bounded by how well a linear model fits your reward surface, a quantity you can estimate offline on the logger's own data before trusting any estimate built on it, and almost nobody does.
Report the effective sample size next to every off-policy estimate or do not report the estimate. Kish's ESS, `(sum w)^2 / sum w^2`, converts a set of importance weights into the number of equally-weighted observations they are worth, and in the table above it is 39 out of 12,000 logged rounds for the epsilon-greedy logger. That is a 308-fold reduction and it is the entire explanation for why those estimates are off by 65% to 96%. Without it, a reviewer sees five estimates clustered between 0.012 and 0.161 and has no way to know that four of them rest on 39 observations; with it, the table interprets itself and the only sensible action is to go and get a better log. The second number to report always is the maximum weight, 266.7 here, because an estimator in which one observation can carry 267 times the weight of another is a mean of 39 numbers one of which is 267 times a Bernoulli draw. The production consequence is the argument for a permanent uniform-random traffic slice: the uniform log's maximum weight is 40 rather than 266.7 and every estimator on it is three to five times more accurate, which is what that slice is buying.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Propensity not logged at decision time | The chosen action feels like the thing to log | Any off-policy estimator is impossible; nobody notices until someone asks for one | Make propensity() part of the policy interface. It cannot be reconstructed later |
| Single-run comparison | A bandit run looks like a deterministic experiment | Decaying epsilon-greedy’s range is 255.5 to 1158.6 across 12 seeds | Minimum 12 seeds; report sd and sem; compare gaps against pooled sem |
| Theoretical exploration constant shipped | It is in the paper | Measured: c = 1.00 gives 1084.28 against 600.09 at 0.10 |
Sweep it, and check the grid brackets the optimum rather than ending at it |
| Realised regret plotted | It is the quantity that pays the bills | The curve is a random walk; two policies’ curves cross repeatedly | Plot pseudo-regret. At a 5% CTR the noise sd is 0.2189 against a signal of 0.05 |
| Reward assumed instantaneous | The simulator has no delay | UCB1 degrades 93% from delay 0 to 600 and LinUCB 50%, while Thompson is flat | Randomised selection self-diversifies under delay; or batch explicitly and accept it |
| Drift conclusions drawn from noise | The “cost of drift” column has a sign | Two policies apparently improved under drift; every diff smaller than its own sd | Sweep the magnitude. The discount breaks even between 0.6 and 1.2 here |
| Importance weights clipped for variance | It is the standard move | Clipped IPS errs -85.5% against unclipped’s +65.0%, landing near the logger’s own value | Report ESS and max weight. Fix the log, not the estimator |
| Bandit shipped where an experiment was wanted | Both answer “which arm is best” | LinUCB leaves 20.8 of 40 arms under 30 pulls; uniform leaves 0 | Decide first whether you want the best arm or the effect of every arm |
Reporting a mean difference without checking it against the across-seed spread, which is how the drift section of this post was wrong in its first draft. At the configured drift magnitude, the measured cost of drift was +35.32 for LinUCB, +7.34 for epsilon-greedy, +68.32 for decaying epsilon-greedy, and NEGATIVE 26.60 for UCB1 and NEGATIVE 6.48 for discounted LinUCB. Two policies performing better in a harder world is the signature of an effect that is not there, and the across-seed standard deviations, 67.6 to 221.3, are larger than every one of those differences. The first draft had a paragraph explaining why UCB1 is structurally robust to drift, which was a mechanism invented to explain noise and would have been the most confidently wrong sentence in the post. Sweeping the drift magnitude found the actual threshold: the discounted variant's ratio against plain LinUCB is 1.073 at zero drift, 1.003 at 0.6, 0.876 at 1.2 and 0.704 at 2.0, so the discount is insurance that costs 7% and buys nothing below a threshold the default configuration sits under. The more useful half of that sweep is what happens to plain LinUCB's spread as the drift rises: standard deviation 67.6, then 263.8, then 570.8, then 945.4, while the mean moves only from 631 to 920. The damage depends on whether the arm it locked onto happened to be a drifting one, so the failure is occasional and severe, which is exactly the shape a mean cannot describe and exactly the shape that gets a system paged at 3am twice a quarter.
Scaling and Productionizing
The delay is the first thing that bites, and it reorders the policies. A homepage with 10 million daily impressions and a 20 minute reward lag has a delay of roughly 140,000 rounds, far beyond anything in the sweep.
| Policy | delay=0 | delay=35 | delay=150 | delay=600 | Change |
|---|---|---|---|---|---|
| Thompson beta | 754.4 | 763.2 | 707.8 | 740.7 | -2% |
| Epsilon-greedy | 718.1 | 648.4 | 765.7 | 827.9 | +15% |
| LinUCB | 625.0 | 704.3 | 666.0 | 940.4 | +50% |
| UCB1 | 600.1 | 678.1 | 799.0 | 1156.0 | +93% |
UCB1 goes from best at zero delay to worst at 600, and nothing about the algorithm changed. The mechanism is clean: a delay of D means D decisions are made before any of them informs the policy, so a deterministic argmax repeats its single current best guess D times, while a posterior sample draws a different arm each round and self-diversifies for free. Thompson sampling is structurally immune to delay and this is the strongest practical argument for it, stronger than its regret bound.
The parameter count is the second. LinUCB maintains a d by d inverse per arm, so at 2,000 features and 10,000 arms that is 10,000 matrices of 4 million floats, or 160 GB. Back of envelope for the shipped configuration against a realistic one:
this post: 40 arms x 12 feat -> 40 inverses of 144 floats = 23 KB
realistic: 10,000 arms x 2,000 -> 10,000 of 4,000,000 floats = 160 GB
the fix is not engineering: it is HYBRID LinUCB, where most of the
coefficient vector is shared across arms and only a small per-arm part is
disjoint, which also solves the new-arm problem since a new arm inherits
the shared part instead of starting from a flat prior
sample size: 480 coefficients need 480 / 0.0505 = 9,505 rounds minimum
9.6M coefficients need 190M rounds, which is 19 days at 10M/day
and is longer than the world holds still
That last line is the real scaling limit and it is not a compute limit. The relevant horizon is not the traffic volume, it is the time over which tastes and the catalogue hold still, so a service doing 10 million impressions a day whose content turns over weekly has an effective horizon of 70 million rounds no matter how fast it grows.
The monitoring signal for silent degradation is the per-arm pull distribution, tracked daily, not the click-through rate. A bandit that has broken does not usually show a CTR drop, because its failure mode is premature convergence and a prematurely converged policy is serving its current best guess, which is usually decent. What changes is the shape of the allocation: the companion codebase measures greedy, the degenerate case, taking 99.3% of traffic on one arm and leaving 38.2 of 40 arms under 30 pulls. Alert on the top arm’s traffic share crossing a ceiling and on the count of arms below the exposure floor, both of which move within hours and neither of which requires knowing whether the policy is right.
LinUCB is Li, Chu, Langford and Schapire's 2010 Yahoo News paper, which ran it on the Today Module front page and introduced the unbiased offline replay evaluation this post measures at +4.8% error, specifically because they had a uniformly-random traffic bucket to run it on. Thompson sampling's modern revival is Chapelle and Li 2011 at Yahoo, which is the paper that measured its robustness to delayed feedback directly and is the origin of the practical preference for it over UCB in ad serving. Microsoft's Decision Service, described in Agarwal et al. 2016, is the most complete published production system: its central argument is precisely the pitfall table above, that the hard part is not the algorithm but logging the propensity correctly and keeping the exploration honest enough that off-policy evaluation remains possible. Netflix's artwork personalisation work is the clearest public example of the hybrid-LinUCB structure at catalogue scale, and Yandex's and Spotify's published work on counterfactual evaluation both ended in the same place: a permanent randomised traffic slice, maintained as infrastructure, because every estimator degrades faster than anyone expects when the logging policy gets good.
Alternative Approaches
| Approach | Regret | Clicks | Arms left unevaluable | Learns the effect of every arm? | Best-fit scenario |
|---|---|---|---|---|---|
| Fixed-split A/B test | 1153.67 | 646 | 0 of 40 | Yes, all of them | You need an effect size per arm for a decision outside the system |
| Explore-then-commit, 25% | 856.53 | 946 | 0 of 40 | Yes, during the explore phase | A short horizon with a hard freeze date, and a need for both |
| Epsilon-greedy 0.10 | 689.18 | 1106 | 5 of 40 | Partly: the floor keeps all arms sampled | Default. Short horizon, few arms, no usable context |
| Thompson sampling | 744.11 | 1054 | 0 of 40 | Partly | Delayed feedback. Immune at -2% where UCB1 loses 93% |
| UCB1, swept | 589.48 | 1204 | 17.4 of 40 | No | Low delay, stationary, and you can tolerate the spread |
| LinUCB, swept | 631.37 | 1162 | 20.8 of 40 | No | Horizon well past 9,505 rounds, and context genuinely predictive |
The A/B test row is not a straw man and the last two columns are what it is buying. It has the worst regret on the page, by 96%, and it is the only design that ends the horizon able to say something about every arm. A bandit’s entire mechanism is to stop sampling arms that look bad, so it necessarily ends with little to say about them, and the companion codebase measures that at 20.8 of 40 arms under 30 pulls for the best-performing policy. If the question is “which rail should go above the fold” a bandit is correct. If the question is “what is the effect of each rail, because marketing needs to decide which to commission more of”, a bandit answers a different question and answers it in a way that forecloses the one that was asked.
The Beta(1, 12) prior in the Thompson row is doing more work than the algorithm choice and it is the one free lunch in this post. Beta(1, 1) is uniform on the unit interval, which is a belief that a brand-new rail might click 90% of the time, so a policy holding it over-explores for hundreds of rounds chasing a possibility the business knows to be absurd. Beta(1, 12) has a prior mean of 1/13, or 0.077, which is roughly the base rate anyone with a dashboard already knows. This is informative-prior reasoning and it is available in every real deployment and used in almost none, because the default in every library is the uninformative one and nobody reads it as a modelling choice. The general version applies well past bandits: an uninformative prior is not a neutral choice, it is the specific and usually false claim that you know nothing, and in a low-base-rate problem it is the claim that costs the most. If you know the CTR is around 5%, encode it; the cost of being somewhat wrong about it is a few hundred rounds and the cost of pretending not to know is the entire exploration budget.
What we would actually ship: Thompson sampling with a Beta(1, 12) prior, at 744.11 against the best measured 589.48. It gives up 26% of the achievable regret reduction relative to UCB1 and buys three things that matter more in production than 155 units of simulated regret. It is immune to the delay, which is the constraint that reorders everything else and which at real volume is three orders of magnitude worse than anything swept here. It has no exploration constant to get wrong, which given that the published constants are 10 to 50 times too large is worth more than it sounds. And it leaves 0 of 40 arms unevaluable, so next quarter’s off-policy evaluation of the next candidate is still possible. The switch to LinUCB happens on one trigger: when the per-arm sample size clears the 480 / 0.0505 threshold with room to spare and a holdout confirms the context is predictive, which is a measurement rather than a judgement.
Key Takeaways
- A bandit writes the training set for its own successor, so the evaluation methodology is the subject rather than a section. Posts 21 through 27 could hold out a temporal slice; there is no held-out slice of a counterfactual.
- Read the sd column before the regret column. Decaying epsilon-greedy’s range across 12 seeds is 255.5 to 1158.6, and UCB1’s apparent win over LinUCB, 589.48 against 631.37, is 0.87 pooled standard errors and therefore not a finding.
- The exploration constant matters more than the choice of algorithm. LinUCB at the commonly cited
alpha = 0.45scores 837.78 and loses to epsilon-greedy’s 718.11; at the swept 0.02 it scores 631.37 and wins. Theory’sc = 1.00andv = 1.00are the worst values measured in their rows. - A sweep whose argmin is its first grid point has found a wall, not an optimum. All four of our original sweeps did this, and the comparison downstream was one tuned policy against three untuned ones.
- Context pays for itself at a horizon, not in principle. 480 coefficients at a 0.0505 CTR need a healthy multiple of 9,505 rounds; the measured crossover sits between 3,000 and 12,000, with the LinUCB-to-epsilon ratio going 1.201, 0.870, 0.806, 0.687.
- Delayed reward reorders the policies and randomised selection is the defence. UCB1 degrades 93% from delay 0 to 600 while Thompson sampling moves -2%, because a deterministic argmax repeats its best guess for the whole delay and a posterior sample self-diversifies.
- Every off-policy estimator was wrong by 18% to 96%, and the crude one was right. Replay, which discards 94% of the log and needs no propensity arithmetic, came within +4.8% and -8.8%. Clipping the weights made things worse, -85.5%, in the direction that looks like success.
- Report the effective sample size or do not report the estimate. 39 usable observations out of 12,000 logged rounds, with a maximum weight of 266.7, is the entire explanation for the estimator table and it is invisible unless you compute it.
The counter-intuitive lesson is the last one inverted. Everything sophisticated in this post underperformed something simple: the doubly robust estimator lost to replay, theory’s exploration constants lost to swept ones by 10 to 50 times, the discounted variant lost to the plain one below a drift threshold, and the contextual policies lost outright to epsilon-greedy until the horizon passed a sample-size bound you can compute on a napkin. None of that is an argument against the sophisticated versions, which are all correct and all win in the regime they were derived for. It is an argument that the regime is the thing to measure first, and that the napkin calculation of coefficients against clicks would have predicted most of these results before any code was written.
Frequently Asked Questions
Q: Why not just run an A/B test? It is simpler and the statistics are understood.
A: Because the cost is fixed in advance at (K - 1) / K of traffic receiving a worse treatment for the whole duration, measured here as 1153.67 regret against 589.48 for the best bandit, a 96% difference. The trade is real in the other direction though: the A/B test ends with 0 of 40 arms unevaluable while the best bandit leaves 20.8, so if you need an effect size per arm rather than just the winner, the test is answering your question and the bandit is foreclosing it.
Q: Why not LinUCB, given that context is clearly predictive here?
A: At this horizon it loses to Thompson sampling once the delay is realistic, and loses to epsilon-greedy entirely if the exploration constant is left at a published default. The deciding arithmetic is 480 coefficients against 0.0505 x T clicks of information: below roughly 9,505 rounds the contextual model is fitting noise, and the measured per-round regret ratio against epsilon-greedy is 1.201 at T=3,000 before becoming 0.687 at T=120,000.
Q: Why not Thompson sampling everywhere, if it is immune to delay?
A: It is the recommendation here, with two caveats. Its mean regret is 744.11 against 589.48 for swept UCB1, so it is giving up real performance in the low-delay stationary case. And the Beta-Bernoulli form is non-contextual, so moving to the linear version reintroduces both the parameter count and an exploration constant, v, whose theoretical value of 1.00 measures 1100.53 against 657.13 at 0.01.
Q: How do I pick the exploration constant without a simulator?
A: Sweep it on a replayed log from a uniformly random traffic slice, which is the only setting where replay is unbiased, and accept the retention cost: 2.34% of the log survived here, so 12,000 rounds became 281. If there is no random slice, the honest answer is that you cannot pick it reliably and should prefer a policy that does not have one, which is the strongest practical argument for Beta-Bernoulli Thompson sampling.
Q: What metric tells me the bandit has silently broken in production?
A: The per-arm pull distribution, not the CTR. A broken bandit’s failure mode is premature convergence, and a prematurely converged policy is serving its current best guess, which is usually decent, so the CTR barely moves. The allocation shape moves immediately: alert on the top arm’s traffic share crossing a ceiling, which greedy takes to 99.3% in the companion codebase, and on the count of arms below the exposure floor, which greedy takes to 38.2 of 40.
Q: Does the drift matter, and do I need the discounted variant?
A: Measure before deciding, because we did not and were wrong. At the configured drift magnitude the cost of drift was smaller than the across-seed spread for every policy and two policies came out apparently better under drift, which is noise with a sign. Sweeping the magnitude put the discount’s break-even between 0.6 and 1.2, where its ratio against plain LinUCB goes 1.003 to 0.876. The more useful signal is the spread: plain LinUCB’s standard deviation goes 67.6, 263.8, 570.8, 945.4 as drift rises while its mean moves only 631 to 920, so the failure is occasional and severe.
Interview Questions
Q: You are asked to replace a 40-way A/B test with a bandit. What do you establish before choosing an algorithm?
Expected depth: the base rate and the gap between the best arm and the field, since every published comparison is downstream of them and a 0.5 base rate result is not a recommender result; the horizon in rounds and whether it exceeds n_arms x n_features / base_rate if context is being considered; the feedback delay in rounds, not minutes; whether the propensity can be logged at decision time; and whether the stakeholder wants the best arm or the effect of every arm, because a bandit forecloses the second.
Q: Derive the IPS estimator, state when it is unbiased, and explain why it fails in practice.
Expected depth: write V(pi) = E_x[sum_a pi(a|x) r(x,a)] and the importance-sampling identity that re-weights logged rewards by pi/mu; state the support condition, that mu must be positive wherever pi is; identify the variance as the practical failure and compute the worst-case weight, 1/mu_min, which at epsilon 0.15 over 40 arms is 267; introduce Kish’s effective sample size and give the measured 39 out of 12,000; and explain why clipping trades variance for a bias that is always downward and always worst for exactly the actions under evaluation, with the measured -85.5%.
Q: Your UCB bandit worked in a backtest and underperforms in production. Give four hypotheses in order of likelihood.
Expected depth: feedback delay, since the backtest almost certainly applied rewards immediately and UCB1 degrades 93% from delay 0 to 600 because a deterministic argmax repeats its best guess for the delay’s duration; the exploration constant, since the published c = 1.00 measures 1084.28 against 600.09 at 0.10; non-stationarity, with the note that a monotonically shrinking confidence interval cannot revisit an arm no matter how much the world changed, and the discount as the fix with its measured break-even; and backtest calibration, since a simulator with a large best-arm gap makes every policy look good and the gap is the hidden variable.
Q: Explain why a linear Thompson sampling implementation does not need a Cholesky decomposition.
Expected depth: write the posterior theta_a ~ N(mu_a, v^2 A_a^-1); observe that the policy uses the draw only through the scalar theta_a . x; derive that a linear functional of a multivariate Gaussian is Gaussian with mean mu_a . x and variance v^2 x^T A_a^-1 x; conclude that one scalar normal draw per arm is exactly equivalent rather than an approximation; and note the two practical consequences, a measured 2.9x speedup of the whole pipeline and the removal of the failure where A_inv loses positive-definiteness through accumulated Sherman-Morrison error.
Q: A colleague’s bandit comparison shows policy A beating policy B by 7%. What do you ask?
Expected depth: how many independent seeds, since a single run is one draw from a wide distribution and decaying epsilon-greedy’s range here is 255.5 to 1158.6; the standard error of each mean and whether 7% exceeds the pooled standard error of the difference, with the worked example that 589.48 against 631.37 is 0.87 pooled sems and therefore not a result; whether pseudo-regret or realised regret was plotted, given a noise-to-signal ratio of four at a 5% CTR; whether both policies’ exploration constants were swept with grids that bracket their optima rather than ending at them; and whether the per-arm allocation was reported, since the better policy may be the one that leaves the log unevaluable.
View full code for this problem