Run an epsilon-greedy multi-armed bandit from fixed random draws

A bandit agent must balance trying arms it knows little about (explore) and pulling the arm that looks best so far (exploit). Epsilon-greedy is the simplest rule, and it is still used for A/B style online tests.

Write epsilon_greedy(rewards, eps, draws, explore_arms).
- rewards: (T, K) array. rewards[t][a] is the reward you would get by pulling arm a at step t.
- draws: length T list of floats in [0, 1). At step t, if draws[t] < eps you explore and pull explore_arms[t]. Otherwise you exploit and pull the arm with the highest current estimate Q (ties: lowest index).
- Start with Q = 0 and counts N = 0 for every arm. After pulling arm a, N[a] += 1 and Q[a] += (r - Q[a]) / N[a] (a running mean).
Return (Q, chosen) where Q is a NumPy float array of length K and chosen is the list of pulled arms.

Signaturedef epsilon_greedy(rewards, eps, draws, explore_arms)

Example

rewards [[1, 2], [1, 2]], eps 0.5, draws [0.9, 0.1], explore_arms [0, 1]. Step 0 exploits arm 0 (tie), Q = [1, 0]. Step 1 explores arm 1, Q = [1, 2]. chosen = [0, 1].

Understand the idea

A bandit agent repeatedly chooses one of K slot machines. It must balance trying arms it knows little about (explore) with pulling the arm that looks best so far (exploit). Epsilon-greedy explores with probability eps and otherwise exploits. Each arm's estimate Q is a running average of the rewards it gave. Worked example: K = 2, eps = 0.2, rewards every step [0, 1], draws [0.5, 0.1, 0.5], explore_arms [0, 1, 0]. Step 0: 0.5 is not < 0.2, so exploit; Q = [0, 0] is a tie, pick arm 0, reward 0, Q[0] = 0. Step 1: 0.1 < 0.2, so explore arm 1, reward 1, Q[1] = 1. Step 2: exploit, arm 1 is best, reward 1, N[1] = 2, Q[1] = 1 + (1 - 1) / 2 = 1. chosen = [0, 1, 1], Q = [0, 1]. Rule: explore when draws[t] < eps, using explore_arms[t]; otherwise take argmax Q with lowest index on ties; then N[a] += 1 and Q[a] += (r - Q[a]) / N[a]. Flipping the comparison makes it explore most of the time. Epsilon-greedy is still used in online experiments and simple recommender exploration.

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

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

  • Sample 1: worked exampleepsilon_greedy([[1, 2], [1, 2]], 0.5, [0.9, 0.1], [0, 1])
  • Sample 2: six steps eps 0.1epsilon_greedy(_R, 0.1, _d, _x)
  • Test 3: eps 0 never exploresepsilon_greedy(_R, 0.0, _d, _x)[1]
  • Test 4: eps 1 always exploresepsilon_greedy(_R, 1.0, _d, _x)