-
Notifications
You must be signed in to change notification settings - Fork 186
/
multiarmed_bandit.py
134 lines (115 loc) · 4.49 KB
/
multiarmed_bandit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""
multiarmed_bandit.py (author: Anson Wong / git: ankonzoid)
We solve the multi-armed bandit problem using a classical epsilon-greedy
agent with reward-average sampling as the estimate to action-value Q.
This algorithm follows closely with the notation of Sutton's RL textbook.
We set up bandit arms with fixed probability distribution of success,
and receive stochastic rewards from each arm of +1 for success,
and 0 reward for failure.
The incremental update rule action-value Q for each (action a, reward r):
n += 1
Q(a) <- Q(a) + 1/n * (r - Q(a))
where:
n = number of times action "a" was performed
Q(a) = value estimate of action "a"
r(a) = reward of sampling action bandit (bandit) "a"
Derivation of the Q incremental update rule:
Q_{n+1}(a)
= 1/n * (r_1(a) + r_2(a) + ... + r_n(a))
= 1/n * ((n-1) * Q_n(a) + r_n(a))
= 1/n * (n * Q_n(a) + r_n(a) - Q_n(a))
= Q_n(a) + 1/n * (r_n(a) - Q_n(a))
"""
import os
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
class Environment:
def __init__(self, probs):
self.probs = probs # success probabilities for each arm
def step(self, action):
# Pull arm and get stochastic reward (1 for success, 0 for failure)
return 1 if (np.random.random() < self.probs[action]) else 0
class Agent:
def __init__(self, nActions, eps):
self.nActions = nActions
self.eps = eps
self.n = np.zeros(nActions, dtype=np.int) # action counts n(a)
self.Q = np.zeros(nActions, dtype=np.float) # value Q(a)
def update_Q(self, action, reward):
# Update Q action-value given (action, reward)
self.n[action] += 1
self.Q[action] += (1.0/self.n[action]) * (reward - self.Q[action])
def get_action(self):
# Epsilon-greedy policy
if np.random.random() < self.eps: # explore
return np.random.randint(self.nActions)
else: # exploit
return np.random.choice(np.flatnonzero(self.Q == self.Q.max()))
# Start multi-armed bandit simulation
def experiment(probs, N_episodes):
env = Environment(probs) # initialize arm probabilities
agent = Agent(len(env.probs), eps) # initialize agent
actions, rewards = [], []
for episode in range(N_episodes):
action = agent.get_action() # sample policy
reward = env.step(action) # take step + get reward
agent.update_Q(action, reward) # update Q
actions.append(action)
rewards.append(reward)
return np.array(actions), np.array(rewards)
# Settings
probs = [0.10, 0.50, 0.60, 0.80, 0.10,
0.25, 0.60, 0.45, 0.75, 0.65] # bandit arm probabilities of success
N_experiments = 10000 # number of experiments to perform
N_steps = 500 # number of steps (episodes)
eps = 0.1 # probability of random exploration (fraction)
save_fig = True # save file in same directory
output_dir = os.path.join(os.getcwd(), "output")
# Run multi-armed bandit experiments
print("Running multi-armed bandits with nActions = {}, eps = {}".format(len(probs), eps))
R = np.zeros((N_steps,)) # reward history sum
A = np.zeros((N_steps, len(probs))) # action history sum
for i in range(N_experiments):
actions, rewards = experiment(probs, N_steps) # perform experiment
if (i + 1) % (N_experiments / 100) == 0:
print("[Experiment {}/{}] ".format(i + 1, N_experiments) +
"n_steps = {}, ".format(N_steps) +
"reward_avg = {}".format(np.sum(rewards) / len(rewards)))
R += rewards
for j, a in enumerate(actions):
A[j][a] += 1
# Plot reward results
R_avg = R / np.float(N_experiments)
plt.plot(R_avg, ".")
plt.xlabel("Step")
plt.ylabel("Average Reward")
plt.grid()
ax = plt.gca()
plt.xlim([1, N_steps])
if save_fig:
if not os.path.exists(output_dir): os.mkdir(output_dir)
plt.savefig(os.path.join(output_dir, "rewards.png"), bbox_inches="tight")
else:
plt.show()
plt.close()
# Plot action results
for i in range(len(probs)):
A_pct = 100 * A[:,i] / N_experiments
steps = list(np.array(range(len(A_pct)))+1)
plt.plot(steps, A_pct, "-",
linewidth=4,
label="Arm {} ({:.0f}%)".format(i+1, 100*probs[i]))
plt.xlabel("Step")
plt.ylabel("Count Percentage (%)")
leg = plt.legend(loc='upper left', shadow=True)
plt.xlim([1, N_steps])
plt.ylim([0, 100])
for legobj in leg.legendHandles:
legobj.set_linewidth(4.0)
if save_fig:
if not os.path.exists(output_dir): os.mkdir(output_dir)
plt.savefig(os.path.join(output_dir, "actions.png"), bbox_inches="tight")
else:
plt.show()
plt.close()