#299LinUCB Contextual BanditHardStatisticsAgentic AIAsked atMicrosoft · Meta · Google
LinUCB Contextual Bandit
Background
LinUCB is a contextual bandit for personalised recommendations. Each arm learns a linear model over the context vector; arm selection adds an upper confidence bound bonus proportional to the model's uncertainty in the current context direction. Classic baseline behind ad ranking and news personalisation.
Problem statement
Implement LinUCB(n_arms, d, alpha=1.0) with:
choose(x)— returnintarm index with the highest UCB score:
update(arm, x, reward)— Bayesian-style update: , .
Input
n_arms—int >= 1, number of arms.d—int >= 1, context dimension.alpha—float > 0, exploration weight (default ).choose(x)—xis a length- array.update(arm, x, reward)—armin ,xlength-,rewardscalar.
Output
choosereturns anintarm index.updatereturnsNone(mutates state).
Examples
Example 1 — cold start: all arms tied → arm 0
b = LinUCB(3, d=2)
b.choose([1.0, 0.0]) # -> 0 (tie-break by lower index)
Example 2 — positive reward shifts preference
b = LinUCB(2, d=2, alpha=0.01)
for _ in range(6): b.update(1, [1.0, 0.0], 10.0)
b.choose([1.0, 0.0]) # -> 1
Constraints
Ainitialised to identity for each arm;binitialised to zero.alphacontrols exploration vs exploitation; higher = more exploration.- Same input from a deterministic state returns the same arm.
Notes
- Regret. LinUCB achieves regret under linear reward — provably better than ε-greedy for context dimensions that matter.
- Disjoint vs hybrid. This is the disjoint variant (separate per arm). Hybrid LinUCB shares a common across arms plus per-arm .
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: cold start picks arm 0
- •Example: positive reward shifts choice to arm 1
- •Sample: no exploration favors the rewarded arm