-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbandits.py
222 lines (184 loc) · 6.28 KB
/
bandits.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
"""Bandit algorithms."""
from abc import ABC, abstractmethod
import numpy as np
class Bandit(ABC):
"""Base class for bandit algorithms."""
@abstractmethod
def __init__(self, k: int, label: str) -> None:
"""
Initialize the bandit.
Args:
k: Number of arms.
label: The label for the bandit.
"""
@abstractmethod
def select_arm(self) -> int:
"""
Select an arm.
Returns:
The index of the arm to select.
"""
@abstractmethod
def update(self, arm: int, reward: float) -> None:
"""
Update the bandit with the reward for an arm.
Args:
arm: The index of the arm.
reward: The reward for the arm.
"""
class GreedyBandit(Bandit):
"""Greedy bandit algorithm."""
def __init__(
self, k: int, label: str, hold: int = 0, seed: int = 42
) -> None:
"""
Initialize the bandit.
Args:
k: Number of arms.
label: The label for the bandit used for plotting.
hold: Number of times to hold the selected arm before exploring.
Default is `0` (no holding).
seed: The random seed for reproducibility. Default is `42`.
"""
self.k = k
self.label = label
self.hold = hold
self.rng = np.random.default_rng(seed=seed)
self.rew_est = np.zeros(k)
self.counts = np.zeros(k)
self.rewards = []
self.hold_count = 0
self.hold_arm = None
def select_arm(self) -> int:
"""
Select an arm.
Returns:
The index of the arm to select.
"""
# Hold the arm for a number of times before exploring
if self.hold_arm is not None and self.hold_count < self.hold:
self.hold_count += 1
return self.hold_arm
# Explore new arms
else:
self.hold_count = 1
max_reward = np.max(self.rew_est)
max_indices = np.where(self.rew_est == max_reward)[0]
self.hold_arm = self.rng.choice(max_indices)
return self.hold_arm
def update(self, arm: int, reward: float) -> None:
"""
Update the bandit with the reward for an arm.
Args:
arm: The index of the arm.
reward: The reward for the arm.
"""
self.counts[arm] += 1
self.rew_est[arm] += (reward - self.rew_est[arm]) / self.counts[arm]
self.rewards.append(reward)
class EpsilonGreedyBandit(Bandit):
"""Epsilon greedy bandit algorithm."""
def __init__(
self, k: int, label: str, epsilon: float, hold: int = 0, seed: int = 42
) -> None:
"""
Initialize the bandit.
Args:
k: Number of arms.
label: The label for the bandit used for plotting.
hold: Number of times to hold the selected arm before exploring.
Default is `0` (no holding).
epsilon: The probability of exploration.
seed: The random seed for reproducibility. Default is `42`.
"""
self.k = k
self.label = label
self.epsilon = epsilon
self.hold = hold
self.rng = np.random.default_rng(seed=seed)
self.rew_est = np.zeros(k)
self.counts = np.zeros(k)
self.rewards = []
self.hold_count = 0
self.hold_arm = None
def select_arm(self) -> int:
"""
Select an arm.
Returns:
The index of the arm to select.
"""
if self.hold_arm is not None and self.hold_count < self.hold:
self.hold_count += 1
return self.hold_arm
else:
self.hold_count = 1
if self.rng.random() < self.epsilon:
self.hold_arm = self.rng.integers(self.k)
return self.hold_arm
max_reward = np.max(self.rew_est)
max_indices = np.where(self.rew_est == max_reward)[0]
self.hold_arm = self.rng.choice(max_indices)
return self.hold_arm
def update(self, arm: int, reward: float) -> None:
"""
Update the bandit with the reward for an arm.
Args:
arm: The index of the arm.
reward: The reward for the arm.
"""
self.counts[arm] += 1
self.rew_est[arm] += (reward - self.rew_est[arm]) / self.counts[arm]
self.rewards.append(reward)
class UpperConfidenceBoundBandit(Bandit):
"""Upper confidence bound bandit algorithm."""
def __init__(
self, k: int, label: str, c: float, hold: int = 0, seed: int = 42
) -> None:
"""
Initialize the bandit.
Args:
k: Number of arms.
label: The label for the bandit used for plotting.
c: The exploration parameter.
hold: Number of times to hold the selected arm before exploring.
Default is `0` (no holding).
seed: The random seed for reproducibility. Default is `42`.
"""
self.k = k
self.label = label
self.c = c
self.hold = hold
self.rng = np.random.default_rng(seed=seed)
self.rew_est = np.zeros(k)
self.counts = np.zeros(k)
self.rewards = []
self.hold_count = 0
self.hold_arm = None
def select_arm(self) -> int:
"""
Select an arm.
Returns:
The index of the arm to select.
"""
if self.hold_arm is not None and self.hold_count < self.hold:
self.hold_count += 1
return self.hold_arm
else:
t = np.sum(self.counts) + 1
ucb = self.rew_est + self.c * np.sqrt(
np.log(t) / (self.counts + 1e-5)
)
max_reward = np.max(ucb)
max_indices = np.where(ucb == max_reward)[0]
self.hold_arm = self.rng.choice(max_indices)
return self.hold_arm
def update(self, arm: int, reward: float) -> None:
"""
Update the bandit with the reward for an arm.
Args:
arm: The index of the arm.
reward: The reward for the arm.
"""
self.counts[arm] += 1
self.rew_est[arm] += (reward - self.rew_est[arm]) / self.counts[arm]
self.rewards.append(reward)