Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

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 tt the learner observes a context xtx_t, whatever is known about the visitor, patient or query, chooses an arm At∈{1,…,K}A_t\in\{1,\dots,K\}, and observes the reward RtR_t of that arm only. In the stochastic contextual bandit, contexts are drawn independently from a distribution D\mathcal D, and E[Rt∣xt,At=a]=f⋆(xt,a)\E[R_t\mid x_t,A_t=a]=f^\star(x_t,a) for an unknown mean-reward function f⋆f^\star.

A policy is a map π\pi from contexts to arms, with value V(π)=Ex∼D[f⋆(x,π(x))]V(\pi)=\E_{x\sim\mathcal D}\big[f^\star(x,\pi(x))\big]. The best policy plays π⋆(x)=arg max⁡af⋆(x,a)\pi^\star(x)=\argmax_af^\star(x,a) in every context, and the learner is scored against it:

RT  =  E[∑t=1T(f⋆(xt,π⋆(xt))−f⋆(xt,At))]R_T\;=\;\E\Big[\sum_{t=1}^T\Big(f^\star\big(x_t,\pi^\star(x_t)\big)-f^\star(x_t,A_t)\Big)\Big]
Regret against the best policy. When the comparison is restricted to a class Π\Pi of policies, all depth-3 decision trees for example, π⋆\pi^\star becomes the best policy in Π\Pi: the setting of Oracle-Efficient Contextual Bandits. With a single context this is the multi-armed bandit.
Predict before you look

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: 0.6⋅0.10+0.4⋅0.02=0.0680.6\cdot0.10+0.4\cdot0.02=0.068 clicks per visitor, against 0.6⋅0.03+0.4⋅0.08=0.0500.6\cdot0.03+0.4\cdot0.08=0.050 for tech. Showing each reader their own headline earns 0.6⋅0.10+0.4⋅0.08=0.0920.6\cdot0.10+0.4\cdot0.08=0.092. 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: CC separate bandits with regret of order KTc\sqrt{KT_c} each sum, by Cauchy–Schwarz, to as much as CKT\sqrt{CKT}, which is useless when every visitor is new. The way out is generalization: a model of f⋆f^\star 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 E[R∣x,a]=x⊤θa\E[R\mid x,a]=x^\top\theta_a, with xx a dd-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 θa\theta_a by least squares on the rounds where arm aa was played, plays the arm with the highest prediction, and with probability ε\varepsilon a uniformly random arm. It is simple and often competitive, but a fixed ε\varepsilon pays a constant price per round, and decaying ε\varepsilon at the right speed gives regret of order T2/3T^{2/3} (epoch-greedy; Langford & Zhang, 2008). Optimism instead adds to each prediction a bonus measuring how uncertain it is.

DerivationLinUCB from ridge regression
  1. θ^a=(Da⊤Da+λI)−1Da⊤ca=Aa−1ba,Aa=λI+∑x x⊤,ba=∑r x\hat\theta_a=\big(D_a^\top D_a+\lambda I\big)^{-1}D_a^\top\mathbf c_a=A_a^{-1}\mathbf b_a,\qquad A_a=\lambda I+\sum x\,x^\top,\qquad\mathbf b_a=\sum r\,x

    For arm aa, stack the contexts of its rounds as the rows of a matrix DaD_a and their rewards in a vector ca\mathbf c_a. The ridge estimate with regularization λ>0\lambda>0 is

  2. x⊤θ^a−x⊤θa  =  x⊤Aa−1Da⊤η  −  λ x⊤Aa−1θax^\top\hat\theta_a-x^\top\theta_a\;=\;x^\top A_a^{-1}D_a^\top\boldsymbol\eta\;-\;\lambda\,x^\top A_a^{-1}\theta_a

    Write the rewards as ca=Daθa+η\mathbf c_a=D_a\theta_a+\boldsymbol\eta with independent noise of variance σ2\sigma^2. The prediction error at a new context splits into a noise part and a regularization bias:

  3. Var⁡(x⊤θ^a) ≤ σ2∥x∥Aa−12,∥x∥Aa−1=x⊤Aa−1x\Var\big(x^\top\hat\theta_a\big)\ \le\ \sigma^2\norm{x}_{A_a^{-1}}^2,\qquad\norm{x}_{A_a^{-1}}=\sqrt{x^\top A_a^{-1}x}

    The noise part has variance σ2x⊤Aa−1Da⊤DaAa−1x≤σ2x⊤Aa−1x\sigma^2x^\top A_a^{-1}D_a^\top D_aA_a^{-1}x\le\sigma^2x^\top A_a^{-1}x, because Da⊤Da⪯AaD_a^\top D_a\preceq A_a. So the natural width of a prediction is the length of xx measured with Aa−1A_a^{-1}: small in directions in which the arm has seen many contexts, large in directions it has not seen.

  4. At  =  arg max⁡a (xt⊤θ^a+α ∥xt∥Aa−1)A_t\;=\;\argmax_a\ \Big(x_t^\top\hat\theta_a+\alpha\,\norm{x_t}_{A_a^{-1}}\Big)

    LinUCB plays the arm with the largest optimistic prediction. The confidence parameter α\alpha is set of order dlog⁡T\sqrt{d\log T} by theory and tuned in practice:

python
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 * x

Inverting each AaA_a every round costs O(Kd3)\order{Kd^3}; production code updates Aa−1A_a^{-1} with the Sherman–Morrison formula in O(d2)\order{d^2} 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.

Check your understanding

Suppose each context is a one-hot vector ece_c indicating one of CC distinct contexts, and λ=1\lambda=1. What is LinUCB's width ∥x∥Aa−1\norm{x}_{A_a^{-1}} for arm aa in context cc?

  1. 1/1+Na1/\sqrt{1+N_a}, with NaN_a the arm's pulls in all contexts
  2. 1/1+Na,c1/\sqrt{1+N_{a,c}}, with Na,cN_{a,c} the pulls of arm aa in context cc: a separate UCB-style index per context, with no sharing
  3. Zero, because one-hot features carry no uncertainty
  4. The same for every arm, because the contexts are the same
Show the answer

B. 1/1+Na,c1/\sqrt{1+N_{a,c}}, with Na,cN_{a,c} the pulls of arm aa in context cc: a separate UCB-style index per context, with no sharing

With one-hot features Aa=I+diag⁡(Na,1,…,Na,C)A_a=I+\diag(N_{a,1},\dots,N_{a,C}), so ec⊤Aa−1ec=1/(1+Na,c)e_c^\top A_a^{-1}e_c=1/(1+N_{a,c}). Linear features generalize only when contexts share directions; one-hot features share nothing, and LinUCB becomes CC independent bandits, with the CKT\sqrt{CKT} cost that generalization was meant to avoid.

Linear Thompson sampling replaces the bonus by a sample: draw θ~a∼N(θ^a,v2Aa−1)\tilde\theta_a\sim\mathcal N(\hat\theta_a,v^2A_a^{-1}) for each arm and play arg max⁡axt⊤θ~a\argmax_ax_t^\top\tilde\theta_a. 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 α\alpha, proves regret of order dTd\sqrt T, and explains why frequentist analyses of linear Thompson sampling inflate vv.

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 pi=μ(ai∣xi)p_i=\mu(a_i\mid x_i), the probability with which the logged arm was chosen.

DerivationInverse propensity scoring is unbiased
  1. V^IPS(π)  =  1n∑i=1nri π(ai∣xi)pi\hat V_{\mathrm{IPS}}(\pi)\;=\;\frac1n\sum_{i=1}^n r_i\,\frac{\pi(a_i\mid x_i)}{p_i}

    From nn logged rounds (xi,ai,ri,pi)(x_i,a_i,r_i,p_i), estimate the value of a target policy π\pi by reweighting each logged reward by how much more, or less, likely π\pi was to choose the logged arm:

  2. E[r π(a∣x)μ(a∣x)]=Ex[∑aμ(a∣x) π(a∣x)μ(a∣x) f⋆(x,a)]=Ex[∑aπ(a∣x) f⋆(x,a)]=V(π)\E\Big[r\,\frac{\pi(a\mid x)}{\mu(a\mid x)}\Big]=\E_x\Big[\sum_a\mu(a\mid x)\,\frac{\pi(a\mid x)}{\mu(a\mid x)}\,f^\star(x,a)\Big]=\E_x\Big[\sum_a\pi(a\mid x)\,f^\star(x,a)\Big]=V(\pi)

    Take one term. Given the context, the logged arm is drawn from μ\mu and its reward has mean f⋆(x,a)f^\star(x,a), so the propensity cancels the sampling probability:

  3. The cancellation needs μ(a∣x)>0\mu(a\mid x)>0 wherever π(a∣x)>0\pi(a\mid x)>0, 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 π/μ\pi/\mu, 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 f^\hat f by regression and averages f^(x,π(x))\hat f(x,\pi(x)): 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, V^DR=1n∑i[∑aπ(a∣xi)f^(xi,a)+π(ai∣xi)pi(ri−f^(xi,ai))]\hat V_{\mathrm{DR}}=\frac1n\sum_i\big[\sum_a\pi(a\mid x_i)\hat f(x_i,a)+\frac{\pi(a_i\mid x_i)}{p_i}\big(r_i-\hat f(x_i,a_i)\big)\big]: 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.

Check your understanding

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?

  1. Train a click model by regression
  2. Compute unbiased IPS or doubly robust estimates of a new policy's value, unless the propensities can be reconstructed exactly
  3. Count how often each article was shown
  4. 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.

PitfallWhat goes wrongMitigation
Missing or wrong propensitiesIPS and doubly robust estimates become biased, silentlyLog the probability at decision time, from the code that sampled the action
Delayed rewardsPurchases arrive days after a recommendation; recent decisions look worse than they areFix a reward window, join rewards to decisions by an identifier, and learn only from closed windows
Lost overlapActions never explored in some contexts can neither be evaluated nor learned thereKeep a floor on every action's probability
Unlogged featuresIf the logging policy used information missing from the logs, the logged context does not explain the action: confoundingLog every input the policy used
Drift and feedback loopsUsers and items change, and the policy shapes the data it later learns fromRetrain continually, keep exploring, and check estimated values against randomized holdouts
Slates and positionsSeveral items are shown at once, and clicks depend on positionUse position-aware click models or estimators designed for slates
Most failures of deployed contextual bandits are data failures, not algorithmic ones.

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 ∥x∥Aa−1\norm{x}_{A_a^{-1}} 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 π/μ\pi/\mu 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.

Question 1

Against what does a contextual bandit's regret compare the learner's rewards?

  1. The best single arm, chosen in hindsight
  2. The best policy, which may choose a different arm in each context
  3. The highest reward actually observed in each round
  4. 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 π⋆(x)=arg max⁡af⋆(x,a)\pi^\star(x)=\argmax_af^\star(x,a) 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.

Question 2

In LinUCB, what does the bonus α∥x∥Aa−1\alpha\norm{x}_{A_a^{-1}} measure?

  1. The noise level of arm aa's rewards
  2. The number of times arm aa has been pulled, whatever the contexts
  3. The length of the context vector
  4. How poorly arm aa's past contexts cover the direction of the current context
Show the answer

D. How poorly arm aa's past contexts cover the direction of the current context

AaA_a accumulates x x⊤x\,x^\top over the arm's pulls, so ∥x∥Aa−1\norm{x}_{A_a^{-1}} 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.

Question 3

When is the inverse propensity score estimate 1n∑iri π(ai∣xi)/pi\frac1n\sum_ir_i\,\pi(a_i\mid x_i)/p_i of a target policy's value unbiased?

  1. When the logged propensities pip_i are the true probabilities of the logged actions, and every action the target policy may choose had positive logging probability in that context
  2. When the logging policy was deterministic
  3. When the target policy is close to the logging policy
  4. Only when the reward model used for evaluation is correct
Show the answer

A. When the logged propensities pip_i 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 μ(a∣x)⋅π(a∣x)/μ(a∣x)=π(a∣x)\mu(a\mid x)\cdot\pi(a\mid x)/\mu(a\mid x)=\pi(a\mid x), which needs the true μ\mu and μ(a∣x)>0\mu(a\mid x)>0 wherever π(a∣x)>0\pi(a\mid x)>0. Closeness of the policies affects the variance, not the bias, and no reward model is involved.

Question 4

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?

  1. Nothing: the zeros average out over many nights
  2. The model overestimates recent items, which then get shown too often
  3. Recent decisions are systematically undervalued, so the learner is biased against whatever it has shown recently
  4. 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

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