Contextual Bandits
Bandits with side information: recommendations, ads and personalized treatment.
A news site does not have one best headline; it has a best headline for each reader. A contextual bandit sees side information before it chooses, and what it must learn is a policy, a map from contexts to arms, rather than a single best arm. This lesson formalizes the setting, builds LinUCB from ridge regression, turns the logs of a running system into unbiased evaluations of new policies, and lists what it takes to run such a system in production.
What you’ll learn
- Formalize the stochastic contextual bandit, define regret against the best policy, and explain why a context-free bandit cannot achieve low regret against it.
- Derive LinUCB from ridge regression and implement it in NumPy, and compare it with ε-greedy regression and linear Thompson sampling.
- Prove that inverse propensity scoring evaluates a new policy without bias from logged data, and state the overlap condition it needs.
- Identify the pitfalls of deployed systems: propensity logging, delayed rewards, lost overlap, unlogged features and feedback loops.
One best arm per context
In round the learner observes a context , whatever is known about the visitor, patient or query, chooses an arm , and observes the reward of that arm only. In the stochastic contextual bandit, contexts are drawn independently from a distribution , and for an unknown mean-reward function .
A policy is a map from contexts to arms, with value . The best policy plays in every context, and the learner is scored against it:
Sports fans, 60% of visitors, click the sports headline with probability 0.10 and the tech headline with 0.03; tech fans, the other 40%, click them with probability 0.02 and 0.08. How many more clicks per 1,000 visitors does the best policy earn than the best single headline?
Show the answer
24
The sports headline is the best single arm: clicks per visitor, against for tech. Showing each reader their own headline earns . A context-free learner that finds the best arm perfectly still loses 0.024 per visitor, 24 per 1,000, forever: linear regret against the best policy.
With a handful of contexts you could run a separate bandit for each. But the regret adds up across contexts: separate bandits with regret of order each sum, by Cauchy–Schwarz, to as much as , which is useless when every visitor is new. The way out is generalization: a model of that lets what was learned about one visitor inform decisions about similar ones.
Regression plus optimism: LinUCB
Generalization needs a model class. The simplest useful one is linear: give each arm a parameter vector and model , with a -dimensional feature vector. Li, Chu, Langford and Schapire (2010) call this the disjoint model; their hybrid model adds features shared by all arms. Two strategies follow.
ε-greedy with regression fits each by least squares on the rounds where arm was played, plays the arm with the highest prediction, and with probability a uniformly random arm. It is simple and often competitive, but a fixed pays a constant price per round, and decaying at the right speed gives regret of order (epoch-greedy; Langford & Zhang, 2008). Optimism instead adds to each prediction a bonus measuring how uncertain it is.
For arm , stack the contexts of its rounds as the rows of a matrix and their rewards in a vector . The ridge estimate with regularization is
Write the rewards as with independent noise of variance . The prediction error at a new context splits into a noise part and a regularization bias:
The noise part has variance , because . So the natural width of a prediction is the length of measured with : small in directions in which the arm has seen many contexts, large in directions it has not seen.
LinUCB plays the arm with the largest optimistic prediction. The confidence parameter is set of order by theory and tuned in practice:
import numpy as np
class LinUCB:
"""Disjoint LinUCB (Li, Chu, Langford & Schapire, 2010): one ridge regression per arm."""
def __init__(self, n_arms, d, alpha=1.0, lam=1.0):
self.alpha = alpha
self.A = np.stack([lam * np.eye(d) for _ in range(n_arms)]) # A_a = lam*I + sum x x^T
self.b = np.zeros((n_arms, d)) # b_a = sum r x
def choose(self, x):
scores = []
for A_a, b_a in zip(self.A, self.b):
A_inv = np.linalg.inv(A_a)
theta = A_inv @ b_a # ridge estimate
width = np.sqrt(x @ A_inv @ x) # ||x|| in the A_a^{-1} norm
scores.append(x @ theta + self.alpha * width)
return int(np.argmax(scores))
def update(self, a, x, r):
self.A[a] += np.outer(x, x)
self.b[a] += r * xInverting each every round costs ; production code updates with the Sherman–Morrison formula in per update. On the Yahoo! Today Module front page, with over 33 million logged events, Li et al. reported a 12.5% click lift over a context-free bandit, and a larger advantage when data were scarce.
Suppose each context is a one-hot vector indicating one of distinct contexts, and . What is LinUCB's width for arm in context ?
- , with the arm's pulls in all contexts
- , with the pulls of arm in context : a separate UCB-style index per context, with no sharing
- Zero, because one-hot features carry no uncertainty
- The same for every arm, because the contexts are the same
Show the answer
B. , with the pulls of arm in context : a separate UCB-style index per context, with no sharing
With one-hot features , so . Linear features generalize only when contexts share directions; one-hot features share nothing, and LinUCB becomes independent bandits, with the cost that generalization was meant to avoid.
Linear Thompson sampling replaces the bonus by a sample: draw for each arm and play . Chapelle and Li (2011) used the same idea with a logistic click model and a Laplace approximation for display advertising. Linear Bandits: LinUCB & OFUL derives the confidence ellipsoid behind , proves regret of order , and explains why frequentist analyses of linear Thompson sampling inflate .
Learning from logs
A deployed system produces logs: for each decision, the context, the arm chosen and its reward. Can those logs evaluate a policy that was never run? Only if they also record the logging policy's propensity , the probability with which the logged arm was chosen.
From logged rounds , estimate the value of a target policy by reweighting each logged reward by how much more, or less, likely was to choose the logged arm:
Take one term. Given the context, the logged arm is drawn from and its reward has mean , so the propensity cancels the sampling probability:
The cancellation needs wherever , called overlap: an arm the logging policy never chooses in some context carries no evidence about what it would have earned there. The variance grows with the ratios , so a target far from the logging policy is estimated poorly. This is the importance sampling of off-policy RL, with episodes of length one.
Two refinements are standard. The direct method fits a reward model by regression and averages : low variance, but biased when the model is wrong. The doubly robust estimator (Dudík, Langford & Li, 2011) uses the model and corrects it with importance weights, : unbiased when the propensities are right, and low in variance when the model is good. With a uniformly random logging policy and a deterministic target, IPS becomes the replay method: keep only the logged rounds in which the target agrees with the logged arm. Li et al. evaluated LinUCB this way on their logged traffic. These estimators are the subject of Off-Policy Evaluation.
A team logged which article each visitor saw and whether they clicked, but not the probability with which the article was chosen. The logging policy mixed a trained model with ε-greedy exploration whose settings changed several times. What can they not do with these logs?
- Train a click model by regression
- Compute unbiased IPS or doubly robust estimates of a new policy's value, unless the propensities can be reconstructed exactly
- Count how often each article was shown
- Estimate each article's click rate among the visitors who saw it
Show the answer
B. Compute unbiased IPS or doubly robust estimates of a new policy's value, unless the propensities can be reconstructed exactly
Every importance-weighted estimator divides by the probability of the logged action, and with a policy that changed over time, those probabilities cannot be recovered from the actions alone. The other analyses remain possible, but they describe the logged traffic, not what a new policy would earn: a click model fitted to non-random logs can be biased in exactly the contexts where the old policy rarely explored.
Contextual bandits in production
Agarwal et al. (2016) describe the Decision Service, which they present as the first general system for contextual learning, built around four abstractions connected in a loop: explore, choosing actions with known, nonzero probabilities; log, recording the context, the action, its propensity and, later, the reward; learn, updating a policy off-policy from the logs; and deploy, serving the updated policy. They reported click-through gains of 25–30% in content recommendation and an 18% revenue lift on a landing page, and they single out incorrect data collection and weak debuggability as what makes such systems hard. The open-source learning system Vowpal Wabbit, from one of the paper's authors, implements contextual-bandit exploration by reduction to supervised learning, with ε-greedy (the default), bagging, online cover, softmax and SquareCB among its options.
| Pitfall | What goes wrong | Mitigation |
|---|---|---|
| Missing or wrong propensities | IPS and doubly robust estimates become biased, silently | Log the probability at decision time, from the code that sampled the action |
| Delayed rewards | Purchases arrive days after a recommendation; recent decisions look worse than they are | Fix a reward window, join rewards to decisions by an identifier, and learn only from closed windows |
| Lost overlap | Actions never explored in some contexts can neither be evaluated nor learned there | Keep a floor on every action's probability |
| Unlogged features | If the logging policy used information missing from the logs, the logged context does not explain the action: confounding | Log every input the policy used |
| Drift and feedback loops | Users and items change, and the policy shapes the data it later learns from | Retrain continually, keep exploring, and check estimated values against randomized holdouts |
| Slates and positions | Several items are shown at once, and clicks depend on position | Use position-aware click models or estimators designed for slates |
Key takeaways
- A contextual bandit observes a context, chooses an arm and sees only that arm's reward. Its target is the best policy, a map from contexts to arms, and a learner that ignores the context loses a constant amount per round against it.
- Generalizing across contexts needs a model. ε-greedy regression is simple but explores blindly; LinUCB adds a width from ridge regression, small in directions the arm's data already cover, and linear Thompson sampling samples instead.
- Logged data can evaluate a new policy if the propensities were logged: IPS reweights rewards by and is unbiased under overlap; the direct method trades bias for variance, and the doubly robust estimator combines the two.
- Production systems close an explore–log–learn–deploy loop. Their typical failures are data failures: missing propensities, delayed rewards, lost overlap, unlogged features and feedback loops.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Against what does a contextual bandit's regret compare the learner's rewards?
- The best single arm, chosen in hindsight
- The best policy, which may choose a different arm in each context
- The highest reward actually observed in each round
- The average reward of all arms
Show the answer
B. The best policy, which may choose a different arm in each context
The benchmark plays in every context. Comparing only with the best single arm would let a learner that ignores the context look good while it forgoes the gain that the context makes possible.
In LinUCB, what does the bonus measure?
- The noise level of arm 's rewards
- The number of times arm has been pulled, whatever the contexts
- The length of the context vector
- How poorly arm 's past contexts cover the direction of the current context
Show the answer
D. How poorly arm 's past contexts cover the direction of the current context
accumulates over the arm's pulls, so is small when similar contexts have been seen often with this arm and large for new directions. That is what lets LinUCB generalize: evidence about one visitor counts for similar visitors.
When is the inverse propensity score estimate of a target policy's value unbiased?
- When the logged propensities are the true probabilities of the logged actions, and every action the target policy may choose had positive logging probability in that context
- When the logging policy was deterministic
- When the target policy is close to the logging policy
- Only when the reward model used for evaluation is correct
Show the answer
A. When the logged propensities are the true probabilities of the logged actions, and every action the target policy may choose had positive logging probability in that context
Unbiasedness comes from the cancellation , which needs the true and wherever . Closeness of the policies affects the variance, not the bias, and no reward model is involved.
Rewards are purchases that can arrive up to a week after a recommendation. Every night the team retrains on all decisions so far, counting items not yet purchased as zero reward. What goes wrong?
- Nothing: the zeros average out over many nights
- The model overestimates recent items, which then get shown too often
- Recent decisions are systematically undervalued, so the learner is biased against whatever it has shown recently
- Only the variance increases; the estimates stay unbiased
Show the answer
C. Recent decisions are systematically undervalued, so the learner is biased against whatever it has shown recently
A decision made yesterday has had one day to earn its purchase, one made last month has had all week. Counting the missing purchases as zeros biases recent rewards downward, and since what was shown recently is not a random sample of items, the bias steers learning. A fixed reward window, with only closed windows used for training, removes it.
Go deeper
- Linear Bandits: LinUCB & OFUL · Confidence ellipsoids, the elliptical potential lemma and √T regret in d dimensions.
- Oracle-Efficient Contextual Bandits · Reducing exploration to regression: from ε-greedy to SquareCB.
- Dueling Bandits & Learning from Comparisons · When feedback is a preference between two arms: the road to RLHF.
Further reading
- L. Li, W. Chu, J. Langford & R. E. Schapire, "A contextual-bandit approach to personalized news article recommendation," International Conference on World Wide Web (2010).
- M. Dudík, J. Langford & L. Li, "Doubly robust policy evaluation and learning," International Conference on Machine Learning (2011).
- A. Agarwal, S. Bird, M. Cozowicz, L. Hoang, J. Langford, S. Lee, J. Li, D. Melamed, G. Oshri, O. Ribas, S. Sen & A. Slivkins, "Making contextual decisions with low technical debt," arXiv:1606.03966 (2016).
- T. Lattimore & C. Szepesvári, Bandit Algorithms, ch. 18–19 (Cambridge University Press, 2020).