Pick the next arm with the UCB1 rule

Tree search and bandits both face the same choice: try the option that looks best so far, or the one you know least about. UCB1 adds an exploration bonus that shrinks as an arm gets more visits.

Write ucb1_pick(counts, totals, c=2.0). counts[i] is how many times arm i was pulled, totals[i] is the sum of its rewards.
- Any arm with counts[i] == 0 is picked first (lowest index among them).
- Otherwise score each arm as totals[i] / counts[i] + sqrt(c * ln(N) / counts[i]) where N = sum(counts).
- Return the index with the highest score. Ties go to the lowest index.

Signaturedef ucb1_pick(counts, totals, c=2.0)

Example

ucb1_pick([1, 1], [1.0, 0.0]) returns 0.

Understand the idea

UCB1 picks the arm with the best optimistic guess: its average reward plus a bonus for being uncertain. The bonus is large for arms with few pulls and shrinks as they are pulled more, so an arm that started unlucky still gets another chance. Any arm never pulled is tried first. Worked example: counts [2, 1], totals [1.0, 0.2], c = 2. N = 3, ln 3 = 1.0986. Arm 0: mean 0.5, bonus sqrt(2 * 1.0986 / 2) = 1.0481, score 1.5481. Arm 1: mean 0.2, bonus sqrt(2 * 1.0986 / 1) = 1.4823, score 1.6823. Pick arm 1, even though its mean is lower, because it has been tried less. Rule: if any count is 0, return the lowest such index; otherwise score_i = totals_i / counts_i + sqrt(c * ln(N) / counts_i) with N = total pulls, and return the highest score with the lowest index on ties. Pure greedy (no bonus) can lock onto a bad arm forever. UCB1 is the selection rule inside Monte Carlo tree search (as UCT) and is used in online experiments.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: unvisited firstucb1_pick([3, 0, 2], [2.0, 0.0, 1.0])
  • Sample 2: greedy pickucb1_pick([1, 1], [1.0, 0.0])
  • Test 3: bonus winsucb1_pick([50, 2], [30.0, 1.0])
  • Test 4: smaller c exploitsucb1_pick([50, 2], [30.0, 1.0], c=0.01)
  • Test 5: tie lowest indexucb1_pick([4, 4, 4], [2.0, 2.0, 2.0])