Contextual bandits: the best action can depend on the situation
上下文老虎机
Use disjoint LinUCB on two synthetic contexts and evaluate a frozen policy with correctly sampled replay data.
contextual-banditsA single best button can be the wrong question
Imagine a recommendation experiment with two observable situations, equally frequent. These are synthetic reward probabilities, not user data:
| Situation | Action 0 | Action 1 |
|---|---|---|
| Context 0 | 0.8 | 0.3 |
| Context 1 | 0.2 | 0.9 |
Always choosing action 0 yields expected reward 0.50; always choosing action 1 yields 0.60. A policy that chooses action 0 in context 0 and action 1 in context 1 yields 0.85. The missing ingredient is not a more precise global average. It is using the situation observed before choosing.
A contextual bandit observes context, chooses an action, and receives only that action’s reward. Sutton and Barto introduce this as learning an association between situations and actions. Li, Chu, Langford and Schapire’s 2010 paper formulates the problem for recommendation and presents LinUCB. Silver’s lecture specifies the context-first interaction order.
Features describe what is known before the action
At round t, observe a feature vector x_(t,a) of dimension d for each available action a. Features may describe the context, the action, or their interaction. A policy uses these features and past selected feedback to choose an action. It must not include the current outcome among its inputs.
In disjoint LinUCB, each action has its own unknown coefficient vector theta_a. The modeling assumption is linear conditional mean reward:
“Disjoint” means the coefficients are not shared between actions. Evidence can still generalize across feature vectors within one action’s model. In the toy experiment, both actions see the same one-hot vector: [1,0] for context 0 and [0,1] for context 1. Two separate coordinates can then represent each column of the table exactly. This unusually easy model is not evidence that arbitrary recommendation rewards are linear.
Estimate a reward model for each action
Let D_a contain past feature rows for selected action a, and let y_a contain their observed rewards. With positive ridge parameter lambda, minimize squared error plus a penalty. Expanding the gradient and setting it to zero gives
Positive lambda makes A_a positive definite, including before any observation. The initial zero prediction comes from regularization and b_a=0, not observed failures. We solve linear systems rather than explicitly forming an inverse. Li et al.’s disjoint model uses the same sufficient-statistic structure with an identity regularizer.
LinUCB selects the action with the largest predicted mean plus an exploration bonus:
The scalar alpha≥0 controls the bonus. The quadratic form is large along feature directions that have little information in the current design matrix. It is not simply the total number of pulls: two observations in one direction do not necessarily teach much about an orthogonal direction.
In this demonstration, alpha is a tuning parameter. A statistical confidence guarantee requires conditions on features, noise, parameter size and the chosen coefficient; the displayed square root alone does not establish one for arbitrary adaptive data. Scores may exceed the Bernoulli reward range and are not clipped probabilities. With alpha zero, selection becomes greedy in ridge predictions.
After observing reward r from selected action a, only that action’s statistics change:
These updates follow by appending one row to D_a and one element to y_a. Other action models remain unchanged. A zero reward still contributes the outer product to A_a: it is an observation, not missing data.
Offline evaluation needs a logging protocol
A log contains the context, the action chosen by a logging policy, and its observed reward. The target policy may choose another action, whose reward is missing. Averaging all logged rewards evaluates the logger; pretending unchosen outcomes are zeros creates fabricated evidence.
Li et al.’s replay method offers a simple solution under explicit conditions: independent identically distributed events, a fixed K-action set for this presentation, and uniform action logging independent of the target algorithm’s randomization. For a deterministic frozen target pi(x), keep an event only if the logged action L matches it. Conditional on any context and potential reward vector,
Here mathcal L means probability law. The constant retention probability leaves the context and target-reward distribution unchanged. For learning policies, the paper extends the argument by retaining history only on accepted events; this program evaluates a frozen policy instead of implementing that adaptive evaluator.
To match the stopping convention in the proof, request M accepted events, rather than silently changing the denominator when a finite log runs out. With a sufficiently long i.i.d. uniform stream,
The expected scan count is not a guarantee of finishing after KM rows. The finite implementation raises an error if its supplied stream ends early. A policy chosen by inspecting this same evaluation set would also require a separate treatment of selection; our evaluation uses fresh seeds after the policy is frozen.
Why nonuniform matching can be biased
Suppose contexts remain equally frequent and the target still chooses actions [0,1]. A nonuniform logger happens to match the target with probabilities 0.9 and 0.1 in the two contexts. Retained contexts now occur in proportions 0.9 and 0.1, so
More rows do not remove this bias. Nonuniform logging needs an appropriate correction, such as suitable rejection sampling or propensity-based evaluation with support assumptions. Those estimators are outside this implementation; merely storing a propensity field does not correct an unweighted average.
Train on selected rewards, evaluate on fresh logs
Save the program as contextual.py and run it with Python 3 and NumPy. The repository’s checked environment uses NumPy 1.26.4. LinUCB uses two linear solves per action, validates finite feature shapes and updates only the selected model. The synthetic environment, known-model evaluator and learner have separate roles.
import math
import random
import statistics
def integer(x, name, minimum=0):
if isinstance(x, bool) or not isinstance(x, int) or x < minimum:
raise ValueError(name + ' must be an integer >= ' + str(minimum))
return x
def finite(x, name, low=None, high=None):
if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x):
raise ValueError(name + ' must be finite')
if (low is not None and x < low) or (high is not None and x > high):
raise ValueError(name + ' is outside its domain')
return float(x)
def probabilities(values):
p = [finite(v, 'probability', 0, 1) for v in values]
if not p:
raise ValueError('at least one arm is required')
return p
class Bernoulli:
"""The learner receives only pull(action), never the mean vector."""
def __init__(self, means, seed):
self._means = probabilities(means)
integer(seed, 'seed')
self._streams = [random.Random(seed + 104729 * a) for a in range(len(means))]
def pull(self, action):
integer(action, 'action')
if action >= len(self._means):
raise ValueError('unknown action')
return int(self._streams[action].random() < self._means[action])
def summary(values):
if len(values) < 2:
raise ValueError('at least two independent runs are needed for an SE')
return dict(mean=statistics.mean(values), se=statistics.stdev(values) / math.sqrt(len(values)))
import numpy as np
class LinUCB:
def __init__(self, arms, features, alpha=1., ridge=1.):
integer(arms, 'arms', 1); integer(features, 'features', 1)
self.alpha = finite(alpha, 'alpha', 0); ridge = finite(ridge, 'ridge', 0)
if ridge <= 0: raise ValueError('ridge must be positive')
self.A = np.repeat((ridge * np.eye(features))[None, :, :], arms, axis=0)
self.b = np.zeros((arms, features))
def features(self, x):
v = np.asarray(x, dtype=float)
if v.shape != self.b.shape or not np.isfinite(v).all(): raise ValueError('one finite feature vector per arm required')
return v
def scores(self, x, explore=True):
x = self.features(x); values = []
for a, v in enumerate(x):
theta = np.linalg.solve(self.A[a], self.b[a]); z = np.linalg.solve(self.A[a], v)
variance = float(v @ z)
if variance < -1e-10: raise ArithmeticError('positive-definite quadratic form failed')
values.append(float(v @ theta) + (self.alpha * math.sqrt(max(0., variance)) if explore else 0.))
return values
def select(self, x, explore=True):
return int(np.argmax(self.scores(x, explore)))
def observe(self, action, x, reward):
integer(action, 'action'); x = self.features(x); reward = finite(reward, 'reward', 0, 1)
if action >= len(self.b): raise ValueError('unknown action')
v = x[action]; self.A[action] += np.outer(v, v); self.b[action] += reward * v
def features(context):
integer(context, 'context')
if context not in (0, 1): raise ValueError('unknown context')
v = [0., 0.]; v[context] = 1.
return [list(v), list(v)]
def train(steps=2000, seed=0):
integer(steps, 'steps', 1); integer(seed, 'seed')
means = [[.8, .3], [.2, .9]]; contexts = random.Random(seed + 700001)
envs = [Bernoulli(row, seed + 1009 * c) for c, row in enumerate(means)]
learner = LinUCB(2, 2); loss = 0.; counts = [[0, 0], [0, 0]]
for _ in range(steps):
c = contexts.randrange(2); x = features(c); a = learner.select(x)
learner.observe(a, x, envs[c].pull(a)); counts[c][a] += 1
loss += max(means[c]) - means[c][a]
policy = [learner.select(features(c), explore=False) for c in range(2)]
return dict(policy=policy, counts=counts, pseudoregret=loss,
A=learner.A.tolist(), b=learner.b.tolist(),
predictions=[learner.scores(features(c), explore=False) for c in range(2)],
known_model_policy_value=sum(means[c][policy[c]] for c in range(2)) / 2)
def logged_events(size, seed):
integer(size, 'size'); integer(seed, 'seed')
rng = random.Random(seed + 700001); logger = random.Random(seed + 900001)
means = [[.8, .3], [.2, .9]]; envs = [Bernoulli(row, seed + c * 1009) for c, row in enumerate(means)]
for _ in range(size):
c = rng.randrange(2); a = logger.randrange(2)
yield c, a, envs[c].pull(a)
def replay(policy, events, accepted_target):
integer(accepted_target, 'accepted_target', 1)
if len(policy) != 2: raise ValueError('need two binary actions')
for a in policy:
integer(a, 'policy action')
if a not in (0, 1): raise ValueError('unknown policy action')
accepted = 0; total = 0.; scans = 0
for c, a, r in events:
integer(c, 'context'); integer(a, 'action'); r = finite(r, 'reward', 0, 1)
if c not in (0, 1) or a not in (0, 1): raise ValueError('invalid logged event')
scans += 1
if a == policy[c]:
accepted += 1; total += r
if accepted == accepted_target: return dict(accepted=accepted, scanned=scans, mean=total / accepted)
raise RuntimeError(f'log exhausted after {scans} rows with only {accepted} matches')
def demo():
runs = [train(seed=s) for s in range(12)]; policy = runs[0]['policy']
# This is fresh uniform logging, independent of training and policy selection.
evaluations = [replay(policy, logged_events(5000, 10000 + s), 400) for s in range(30)]
return dict(horizon=2000, seeds=list(range(12)), pseudoregret=summary([r['pseudoregret'] for r in runs]),
single_seed=runs[0], best_context_free_value=.6, context_oracle_value=.85,
replay=dict(policy=policy, target=400, seeds=list(range(10000, 10030)),
reward=summary([r['mean'] for r in evaluations]),
scans=summary([r['scanned'] for r in evaluations])),
biased_match_example=dict(target_value=.85, accepted_context_weights=[.9, .1], match_mean=.81))
if __name__ == '__main__':
import json
print(json.dumps(demo(), indent=2, allow_nan=False))
Training uses alpha 1, ridge 1 and 12 seed labels 0–11, each for 2,000 rounds. Contexts are sampled with probability one-half; rewards use independent per-context, per-action streams. Average path pseudo-regret is 3.05 with standard error about 0.988609 in these easy one-hot instances. This is not a general LinUCB benchmark. The seed-0 learner’s frozen greedy policy is [0,1], whose known-model value is 0.85; the best context-free value is 0.60.
For an independent evaluation, generate uniform logs with seeds 10000–10029 and retain exactly 400 matching events per run. The mean reward estimate is 0.854 with standard error about 0.002417. The mean scan count is about 804.933, near the theoretical expectation 800. Each supplied stream has at most 5,000 rows, and all these runs reach the target. An exhausted stream raises an error instead of presenting a shorter evaluation as equivalent.
A naive dense solve costs O(d³); scanning K actions here therefore costs O(Kd³) per round. Updating one outer product costs O(d²), and the agent stores O(Kd²) matrix state. The one-hot example is tiny; optimized factorizations could reduce repeated work, but the supplied code does not claim to implement them. Frozen-policy replay uses a table lookup per event and constant working memory for this two-context example.
The context must be available, and the model must fit
Contextual bandits model immediate reward selection without planning action-induced changes in future external states. They still learn over time, and an action changes what information is collected. If recommendations also change a user’s later state in a way the objective needs to optimize, an immediate-reward model may omit important effects.
One-hot contexts permit separate estimates but do not automatically generalize to unseen situations. Richer features can generalize, while an incorrect linear model can also spread systematic error. Shared or hybrid coefficient models are different choices from this disjoint implementation.
Uniform logs simplify replay at the cost of discarding many rows. Real logs may have changing action sets, delayed outcomes, unrecorded selection variables or no support for a target action. Check these conditions before transferring the proof. This article does not reproduce the paper’s Yahoo experiment or its reported click lift.
Follow the context through learning and evaluation
-
What are the expected rewards of the two constant actions and the best context-dependent policy in the opening table?
Answer: Constant action 0 gives
(0.8+0.2)/2=0.50; action 1 gives(0.3+0.9)/2=0.60. Choosing[0,1]by context gives(0.8+0.9)/2=0.85. -
Start with
A=I,b=0. For the selected arm, observe feature[1,2]and reward 1. What are the updated statistics and predicted mean at that same feature?Answer:
A=[[2,2],[2,5]],b=[1,2]. Solving gives coefficients[1/6,1/3]; the prediction is1/6+2/3=5/6. The other arm is unchanged. The exploration bonus is additional to this mean. -
With two uniformly logged actions and target 400 accepted events, should replay always stop after exactly 800 rows?
Answer: No. 800 is an expected scan count. Matches are random; continue until 400 are accepted, or report that the finite log was exhausted.
-
Why does the nonuniform logger yield 0.81 rather than 0.85 in the example?
Answer: Matching keeps context 0 nine times as often as context 1. The retained reward average is therefore
0.9×0.8+0.1×0.9=0.81, rather than the target population’s equally weighted 0.85. Correct the sampling mechanism or use a justified estimator; extra biased rows are not the remedy.
Learning and evaluation require different evidence
Li et al. connect arm-specific ridge models to an exploration index and give a replay proof with explicit logging conditions. The working draft and Silver’s lecture explain how context changes the action-selection problem. The original program above checks those mechanisms on synthetic data; the model fit, logging assumptions and reward objective still need evidence in any real application.
Make a prediction, then check
A log chose actions nonuniformly. Is simply averaging matching rewards guaranteed unbiased for a target policy?
Learning objectives
- Compute arm-specific ridge estimates and update only the chosen arm.
- Explain fixed-match replay under uniform logs and demonstrate nonuniform selection bias.
Prerequisites & connections
Explore related knowledge →References
- A Contextual-Bandit Approach to Personalized News Article Recommendation
Lihong Li, Wei Chu, John Langford, Robert E. Schapire · 2010 - Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015 - Lecture 9: Exploration and Exploitation
David Silver · 2015
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 metadata/abstract,2§2.1,3§3.1 and5§4 including Algorithm3/Theorem1 proof; directly viewed4 Algorithm1 and§4 opening. Disjoint LinUCB and fixed accepted-count replay with i.i.d. events and uniform logging. Hybrid model and later experimental tables not audited; abstract12.5% is not a verified reproduction. Teaching alpha is a tuning parameter, not an unrestricted confidence guarantee. PDF60–61 §2.8 contextual action mapping and immediate-reward distinction from a full MDP. Read2026-09-23; implementation/replay sourced to Li2010. Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse. 7 paired equations and four explained exercises. Checked disjoint ridge against batch regression and a hand inverse, chosen-only updates, shape domains, contextual versus fixed-action oracles, fixed accepted-count uniform replay, finite-log exhaustion and nonuniform matching bias. Toy alpha is a tuning parameter, not a general confidence guarantee.
- Checked disjoint ridge against batch regression and a hand inverse, chosen-only updates, shape domains, contextual versus fixed-action oracles, fixed accepted-count uniform replay, finite-log exhaustion and nonuniform matching bias. Toy alpha is a tuning parameter, not a general confidence guarantee.
- Four computed SVG variants per topic;12 numeric/geometry tests and30 responsive cases passed. Ten selected current captures inspected: seven final captures directly viewed, three byte-identical to directly viewed earlier captures; actual byte identity checked. Browser inputs bound by SHA before integration. Full article acceptance recorded separately.
Source locations checked:
- A Contextual-Bandit Approach to Personalized News Article Recommendation · Read PDF1 metadata/abstract,2§2.1,3§3.1 and5§4 including Algorithm3/Theorem1 proof; directly viewed4 Algorithm1 and§4 opening. Disjoint LinUCB and fixed accepted-count replay with i.i.d. events and uniform logging. Hybrid model and later experimental tables not audited; abstract12.5% is not a verified reproduction. Teaching alpha is a tuning parameter, not an unrestricted confidence guarantee.
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF60–61 §2.8 contextual action mapping and immediate-reward distinction from a full MDP. Read2026-09-23; implementation/replay sourced to Li2010.
- Lecture 9: Exploration and Exploitation · Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse.
Related topics