Foundations to Frontier
Tests
B. Statistical Learning Theory › B5 Online learning and bandits

Contextual Bandits

In a contextual bandit, each round brings side information (a context) before the learner acts, and the best action depends on it, so the learner must learn a policy rather than a single best arm. This topic covers the linear contextual bandit and LinUCB (confidence ellipsoids, Õ(d√T) regret), Thompson sampling with linear models, ε-greedy baselines, why ignoring context gives linear regret, and the companion problem of off-policy evaluation from logged data: inverse propensity scoring (unbiased, high variance), the direct method (low variance, biased if the model is wrong) and the doubly robust estimator. In the exercises you race LinUCB against context-blind and greedy baselines and measure the bias–variance trade-off of off-policy estimators.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

The best choice depends on the situation

A rover can drive over terrain in three modes: fast, careful or rocking. No single mode is best everywhere. On flat sand “fast” wins, on rocks “careful” wins. Before each choice the rover sees the terrain (its context), picks a mode, and only finds out how well that mode worked. Over time it must learn a rule mapping terrain to mode, while still trying modes it is unsure about. That’s a contextual bandit: the bandit problem with eyes.

Contextual bandit: the best action depends on the situation
context x₁ → , x₂ ↑regret: bottom LinUCB, middle ε-greedy, top UCB1 (no context)
regret after 800 rounds: LinUCB 3.5 · linear ε-greedy 41.9 · context-blind UCB1 309.1
Background: the truly best of three actions for each context. Dots: the action LinUCB's current estimates would pick there (outlined if wrong). Slide "after round" to watch the map sharpen. A bandit that ignores the context can only find the best single action on average, so it keeps losing in regions where another action is better: linear regret. LinUCB learns a reward model per action and explores where its confidence ellipsoid is wide. α = 0 is greedy and can get stuck; a large α over-explores.
Why engineers care

Contextual bandits personalize decisions with partial feedback: choosing a locomotion gait from terrain features, selecting a planner or sensor configuration from conditions, picking a compression mode from link quality, or recommending content. Logged data from past decisions can also be reused to evaluate a new policy before deploying it (off-policy evaluation), which matters when trying things on hardware is expensive or risky.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A contextual bandit sees … before acting.
  2. 2. The learner must learn…
  3. 3. Feedback is still…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

Protocol and regret

Each round: observe xtx_t, choose ata_t, receive rtr_t with mean μ(xt,at)\mu(x_t, a_t). Regret is measured against the best action for each context:

RegT=∑t=1T(max⁡aμ(xt,a)−μ(xt,at)).\mathrm{Reg}_T = \sum_{t=1}^T\Big(\max_a\mu(x_t, a) - \mu(x_t, a_t)\Big).

An algorithm that ignores contexts can at best find the single best action on average, so its regret against this per-context benchmark grows linearly whenever different contexts favour different actions.

Linear contextual bandits

Assume μ(x,a)=θa⊤x\mu(x, a) = \theta_a^\top x (disjoint model) or θ⊤ϕ(x,a)\theta^\top\phi(x, a) (shared). Each action’s parameters are estimated by ridge regression on the rounds where it was chosen: θ^a=Aa−1ba\hat\theta_a = A_a^{-1}b_a with Aa=λI+∑xx⊤A_a = \lambda I + \sum x x^\top and ba=∑r xb_a = \sum r\,x.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Contextual regret compares with…
  2. 2. A context-blind bandit's regret against that benchmark is typically…
  3. 3. LinUCB estimates each action's θ by…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

LinUCB

Choose

at=arg⁡max⁡a θ^a⊤xt+αxt⊤Aa−1xt.a_t = \arg\max_a\ \hat\theta_a^\top x_t + \alpha\sqrt{x_t^\top A_a^{-1}x_t}.

The bonus is the width of a confidence ellipsoid in direction x: large where that action has seen few similar contexts. With a properly chosen α (from self-normalized concentration, Abbasi-Yadkori, Pál and Szepesvári, 2011), the regret is O~(dT)\tilde O(d\sqrt T). Updates cost O(d2)O(d^2) per round using the Sherman–Morrison formula.

Linear Thompson sampling

Sample θ~a∼N(θ^a,v2Aa−1)\tilde\theta_a\sim\mathcal N(\hat\theta_a, v^2A_a^{-1}) and act greedily on the samples. It has similar guarantees (Agrawal and Goyal, 2013) and often performs better in practice.

Off-policy evaluation (OPE)

Given logs (xi,ai,ri,pi)(x_i, a_i, r_i, p_i) from a logging policy with known propensities pi=μ(ai∣xi)p_i = \mu(a_i\mid x_i), estimate the value of a new policy π:

  • IPS: V^=1n∑i1[ai=π(xi)]piri\hat V = \frac1n\sum_i\frac{\mathbb 1[a_i = \pi(x_i)]}{p_i}r_i. Unbiased, but high variance when propensities are small.
  • Direct method (DM): fit q^(x,a)\hat q(x, a) and average q^(xi,π(xi))\hat q(x_i, \pi(x_i)). Low variance, but biased if q^\hat q is wrong.
  • Doubly robust (DR): 1n∑i[q^(xi,π(xi))+1[ai=π(xi)]pi(ri−q^(xi,ai))]\frac1n\sum_i\Big[\hat q(x_i, \pi(x_i)) + \frac{\mathbb 1[a_i = \pi(x_i)]}{p_i}\big(r_i - \hat q(x_i, a_i)\big)\Big]. Unbiased if either the propensities or the model are correct, and usually lower variance than IPS.
🐍 Exercise 1: LinUCB vs ε-greedy vs context-blind UCB
Simulate a disjoint linear contextual bandit (K = 4 actions, d = 5). Run LinUCB (with Sherman–Morrison updates), linear ε-greedy and context-blind UCB1, and compare their regret against the per-context best action at T = 500 and T = 2000.
📝 Quick check (Level 2)
0/3 answered
  1. 1. LinUCB's exploration bonus is large when…
  2. 2. IPS is…
  3. 3. DR is unbiased if…

Level 3: Advanced

★★★★☆ Advanced⏱ 40 minGraduate level, with full derivations and proofs.

Why IPS is unbiased

For fixed x, Ea∼μ(⋅∣x)[1[a=π(x)]μ(a∣x)r]=μ(π(x)∣x)⋅E[r∣x,π(x)]μ(π(x)∣x)=q(x,π(x))\mathbb E_{a\sim\mu(\cdot|x)}\big[\tfrac{\mathbb 1[a = \pi(x)]}{\mu(a|x)}r\big] = \mu(\pi(x)|x)\cdot\frac{\mathbb E[r\mid x, \pi(x)]}{\mu(\pi(x)|x)} = q(x, \pi(x)), provided μ(π(x)∣x)>0\mu(\pi(x)|x)\gt0 (overlap). Its variance scales like 1/μ(π(x)∣x)1/\mu(\pi(x)|x), which explodes when the logging policy rarely takes the target’s actions.

Why DR is doubly robust

Write DR = DM + an IPS-weighted residual correction. If the propensities are right, the correction’s expectation is q−q^q - \hat q evaluated at π(x), which exactly cancels DM’s bias. If the model is right, the residuals r−q^r - \hat q have mean zero, so the correction is unbiased noise. Its variance is IPS’s applied to residuals rather than raw rewards, so it is smaller when q^\hat q is decent. ∎

Regret of LinUCB (idea)

With high probability, θa\theta_a lies in the ellipsoid {θ:∥θ−θ^a∥Aa≤βt}\{\theta:\|\theta - \hat\theta_a\|_{A_a}\le\beta_t\}, so optimism gives per-round regret at most 2βt∥xt∥A−12\beta_t\|x_t\|_{A^{-1}}. The elliptical potential lemma, ∑tmin⁡(1,∥xt∥At−1−12)≤2dln⁡(1+T/(dλ))\sum_t\min(1, \|x_t\|^2_{A_{t-1}^{-1}})\le2d\ln(1 + T/(d\lambda)), plus Cauchy–Schwarz gives O~(dT)\tilde O(d\sqrt T). ∎

📝 Quick check (Level 3)
0/3 answered
  1. 1. IPS needs the overlap condition…
  2. 2. The elliptical potential lemma bounds…
  3. 3. IPS variance scales like…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Contextual bandits, measured

Exercise 1 (K = 4, d = 5, mean over 3 instances). Regret at T = 500 and T = 2000:

algorithm T = 500 T = 2000
LinUCB 9.4 10.5
linear ε-greedy (ε = 0.1) 31.5 106.8
context-blind UCB1 252.1 991.1

LinUCB’s regret nearly stops growing (and is 11.4 at T = 8000). ε-greedy pays its exploration tax forever. Ignoring context is catastrophic: no single action is best everywhere.

Exercise 2: off-policy evaluation (3 actions, logging probabilities 0.2/0.2/0.6, a deterministic target policy, a deliberately misspecified linear reward model; true value 0.633; 200 datasets per n). Bias and RMSE:

n IPS DM DR
200 −0.004, 0.118 −0.147, 0.160 −0.012, 0.082
1000 −0.002, 0.056 −0.150, 0.152 −0.004, 0.038
5000 +0.004, 0.024 −0.149, 0.149 +0.001, 0.016

The direct method’s bias doesn’t shrink with data: the model is wrong. IPS is unbiased and its error falls like 1/√n. DR is unbiased and has 30–40% lower error than IPS.

🐍 Exercise 2 (research): evaluating a policy from logged data
Generate logged bandit data from a known stochastic logging policy, then estimate a new deterministic policy's value with IPS, a (misspecified) direct method and the doubly robust estimator. Measure bias and RMSE over many datasets for several log sizes.

Contextual bandits in AI, robotics and aerospace

  • Terrain-adaptive locomotion: choose gait or speed from terrain features with partial feedback.
  • Adaptive communications: pick modulation or coding from channel-state context.
  • Safe policy updates: use logged data and DR estimates to vet a new decision rule before flight testing.
  • Bridge to RL: contextual bandits are one-step reinforcement learning; OPE ideas extend to multi-step policies.

References

  1. L. Li, W. Chu, J. Langford, R. E. Schapire (2010). “A contextual-bandit approach to personalized news article recommendation.” WWW.
  2. Y. Abbasi-Yadkori, D. Pál, C. Szepesvári (2011). “Improved algorithms for linear stochastic bandits.” NeurIPS.
  3. S. Agrawal, N. Goyal (2013). “Thompson sampling for contextual bandits with linear payoffs.” ICML.
  4. M. Dudík, J. Langford, L. Li (2011). “Doubly robust policy evaluation and learning.” ICML.
  5. A. Agarwal, D. Hsu, S. Kale, J. Langford, L. Li, R. E. Schapire (2014). “Taming the monster: a fast and simple algorithm for contextual bandits.” ICML.
  6. T. Lattimore, C. Szepesvári (2020). Bandit Algorithms. Cambridge University Press (chapters 18–20).