-
Notifications
You must be signed in to change notification settings - Fork 0
/
bandit.py
330 lines (249 loc) · 8.12 KB
/
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import numpy as np
import utils
class EpsilonGreedyBandit:
def __init__(self, env, epsilon, init=0, alpha=None):
"""
Epsilon-greedy bandit.
:param env: Bandit environment.
:param epsilon: Epsilon (probability of choosing a random action).
:param init: Initial action values.
:param alpha: Alpha for action value sample averages. None means 1 / num_steps.
"""
self.env = env
self.epsilon = epsilon
self.init = init
self.alpha = alpha
self.action_values = None
self.action_counts = None
self.actions = None
self.rewards = None
self.reset()
def act(self):
"""
Take a single action in an environment.
:return: None.
"""
# select an action
r = np.random.uniform(0, 1)
if r > self.epsilon:
action = np.argmax(self.action_values)
else:
action = np.random.randint(0, self.env.num_actions)
# take an action
reward = self.env.act(action)
# update action value
if self.alpha is None:
self.action_values[action] += utils.update_mean(reward, self.action_values[action], self.action_counts[action])
else:
self.action_values[action] += self.alpha * (reward - self.action_values[action])
self.action_counts[action] += 1
# save action and reward
self.actions.append(action)
self.rewards.append(reward)
def reset(self):
"""
Reset the bandit.
:return: None.
"""
self.action_values = np.zeros(self.env.num_actions, dtype=np.float32) + self.init
self.action_counts = np.zeros(self.env.num_actions, dtype=np.int32)
self.actions = []
self.rewards = []
class SoftmaxBandit:
def __init__(self, env, temperature, init=0, alpha=None):
"""
Epsilon-greedy bandit.
:param env: Bandit environment.
:param temperature: Temperate for the softmax (the higher the more random actions).
:param init: Initial action values.
:param alpha: Alpha for action value sample averages. None means 1 / num_steps.
"""
self.env = env
self.temperature = temperature
self.init = init
self.alpha = alpha
self.action_values = None
self.action_counts = None
self.actions = None
self.rewards = None
self.reset()
def act(self):
"""
Take a single action in an environment.
:return: None.
"""
# select an action
softmax = self.__softmax(self.action_values, self.temperature)
action = np.random.choice(range(self.env.num_actions), p=softmax)
# take an action
reward = self.env.act(action)
# update action value
if self.alpha is None:
self.action_values[action] += utils.update_mean(reward, self.action_values[action], self.action_counts[action])
else:
self.action_values[action] += self.alpha * (reward - self.action_values[action])
self.action_counts[action] += 1
# save action and reward
self.actions.append(action)
self.rewards.append(reward)
def reset(self):
"""
Reset the bandit.
:return: None.
"""
self.action_values = np.zeros(self.env.num_actions, dtype=np.float32) + self.init
self.action_counts = np.zeros(self.env.num_actions, dtype=np.int32)
self.actions = []
self.rewards = []
@staticmethod
def __softmax(x, t):
"""
Softmax function.
:param x: Array of values.
:param t: Temperature.
:return: Softmax distribution.
"""
e_x = np.exp(x / t)
return e_x / e_x.sum()
class UCB1Bandit:
def __init__(self, env, init=0, alpha=None):
"""
UCB1 bandit.
:param env: Bandit environment.
:param init: Initial action values.
:param alpha: Alpha for action value sample averages. None means 1 / num_steps.
"""
self.env = env
self.init = init
self.alpha = alpha
self.action_values = None
self.action_counts = None
self.num_plays = None
self.actions = None
self.rewards = None
self.reset()
def act(self):
"""
Take a single action in an environment.
:return: None.
"""
# play each arm once
action = None
for i, count in enumerate(self.action_counts):
if count == 0:
action = i
break
# choose action
if action is None:
values = np.empty(self.env.num_actions)
for i in range(self.env.num_actions):
values[i] = self.action_values[i] + np.sqrt(2 * np.log(self.num_plays) / self.action_counts[i])
action = np.argmax(values)
# take an action
reward = self.env.act(action)
# update action value
if self.alpha is None:
self.action_values[action] += utils.update_mean(reward, self.action_values[action], self.action_counts[action])
else:
self.action_values[action] += self.alpha * (reward - self.action_values[action])
self.action_counts[action] += 1
self.num_plays += 1
# save action and reward
self.actions.append(action)
self.rewards.append(reward)
def reset(self):
"""
Reset the bandit.
:return: None.
"""
self.action_values = np.zeros(self.env.num_actions, dtype=np.float32) + self.init
self.action_counts = np.zeros(self.env.num_actions, dtype=np.int32)
self.num_plays = 0
self.actions = []
self.rewards = []
class UCB2Bandit:
def __init__(self, env, alpha_1, init=0, alpha_2=None):
"""
UCB2 bandit.
:param env: Bandit environment.
:param alpha_1: Alpha parameter for UCB2.
:param init: Initial action values.
:param alpha_2: Alpha for action value sample averages. None means 1 / num_steps.
"""
self.env = env
self.alpha_1 = alpha_1
self.init = init
self.alpha_2 = alpha_2
self.action_values = None
self.action_counts = None
self.rs = None
self.times_to_play = None
self.action_to_play = None
self.num_plays = None
self.actions = None
self.rewards = None
self.reset()
def act(self):
"""
Take a single action in an environment.
:return: None.
"""
# play each arm once
action = None
for i, count in enumerate(self.action_counts):
if count == 0:
action = i
break
# check if there is an action pending
if self.times_to_play is not None and self.times_to_play != 0:
action = self.action_to_play
self.times_to_play -= 1
assert self.times_to_play >= 0
# choose action
if action is None:
values = np.empty(self.env.num_actions)
for i in range(self.env.num_actions):
values[i] = self.action_values[i] + self.__compute_a(self.num_plays, self.rs[i])
action = int(np.argmax(values))
self.action_to_play = action
self.times_to_play = max(self.__compute_tau(self.rs[action] + 1) - self.__compute_tau(self.rs[action]), 1)
# times to play - 1 because the action will be played once at the end of this function
self.times_to_play -= 1
# only add once
self.rs[action] += 1
# take an action
reward = self.env.act(action)
# update action value
if self.alpha_2 is None:
self.action_values[action] += utils.update_mean(reward, self.action_values[action], self.action_counts[action])
else:
self.action_values[action] += self.alpha_2 * (reward - self.action_values[action])
self.action_counts[action] += 1
self.num_plays += 1
# save action and reward
self.actions.append(action)
self.rewards.append(reward)
def reset(self):
"""
Reset the bandit.
:return: None.
"""
self.action_values = np.zeros(self.env.num_actions, dtype=np.float32) + self.init
self.action_counts = np.zeros(self.env.num_actions, dtype=np.int32)
self.rs = np.zeros(self.env.num_actions, dtype=np.int32)
self.times_to_play = 0
self.num_plays = 0
self.actions = []
self.rewards = []
def __compute_tau(self, r):
return int(np.ceil((1.0 + self.alpha_1) ** r))
def __compute_a(self, n, r):
term1 = (1 + self.alpha_1) * np.log((np.e * n) / self.__compute_tau(r))
term2 = 2 * self.__compute_tau(r)
x = np.sqrt(term1 / term2)
if np.isnan(x):
print("NAN")
print(n)
print(term1)
print(term2)
return x