-
Notifications
You must be signed in to change notification settings - Fork 88
/
contextfree.py
271 lines (207 loc) · 8.28 KB
/
contextfree.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
# Copyright (c) Yuta Saito, Yusuke Narita, and ZOZO Technologies, Inc. All rights reserved.
# Licensed under the Apache 2.0 License.
"""Context-Free Bandit Algorithms."""
from dataclasses import dataclass
import os
from typing import Optional
import numpy as np
from sklearn.utils import check_scalar
# import pkg_resources
import yaml
from .base import BaseContextFreePolicy
# configurations to replicate the Bernoulli Thompson Sampling policy used in ZOZOTOWN production
prior_bts_file = os.path.join(os.path.dirname(__file__), "conf", "prior_bts.yaml")
with open(prior_bts_file, "rb") as f:
production_prior_for_bts = yaml.safe_load(f)
@dataclass
class EpsilonGreedy(BaseContextFreePolicy):
"""Epsilon Greedy policy.
Parameters
----------
n_actions: int
Number of actions.
len_list: int, default=1
Length of a list of actions in a recommendation/ranking inferface, slate size.
When Open Bandit Dataset is used, 3 should be set.
batch_size: int, default=1
Number of samples used in a batch parameter update.
random_state: int, default=None
Controls the random seed in sampling actions.
epsilon: float, default=1.
Exploration hyperparameter that must take value in the range of [0., 1.].
policy_name: str, default=f'egreedy_{epsilon}'.
Name of bandit policy.
"""
epsilon: float = 1.0
def __post_init__(self) -> None:
"""Initialize Class."""
check_scalar(self.epsilon, "epsilon", float, min_val=0.0, max_val=1.0)
self.policy_name = f"egreedy_{self.epsilon}"
super().__post_init__()
def select_action(self) -> np.ndarray:
"""Select a list of actions.
Returns
----------
selected_actions: array-like, shape (len_list, )
List of selected actions.
"""
if (self.random_.rand() > self.epsilon) and (self.action_counts.min() > 0):
predicted_rewards = self.reward_counts / self.action_counts
return predicted_rewards.argsort()[::-1][: self.len_list]
else:
return self.random_.choice(
self.n_actions, size=self.len_list, replace=False
)
def update_params(self, action: int, reward: float) -> None:
"""Update policy parameters.
Parameters
----------
action: int
Selected action by the policy.
reward: float
Observed reward for the chosen action and position.
"""
self.n_trial += 1
self.action_counts_temp[action] += 1
self.reward_counts_temp[action] += reward
if self.n_trial % self.batch_size == 0:
self.action_counts = np.copy(self.action_counts_temp)
self.reward_counts = np.copy(self.reward_counts_temp)
@dataclass
class Random(EpsilonGreedy):
"""Random policy
Parameters
----------
n_actions: int
Number of actions.
len_list: int, default=1
Length of a list of actions in a recommendation/ranking inferface, slate size.
When Open Bandit Dataset is used, 3 should be set.
batch_size: int, default=1
Number of samples used in a batch parameter update.
random_state: int, default=None
Controls the random seed in sampling actions.
epsilon: float, default=1.
Exploration hyperparameter that must take value in the range of [0., 1.].
policy_name: str, default='random'.
Name of bandit policy.
"""
policy_name: str = "random"
def compute_batch_action_dist(
self,
n_rounds: int = 1,
) -> np.ndarray:
"""Compute the distribution over actions by Monte Carlo simulation.
Parameters
----------
n_rounds: int, default=1
Number of rounds in the distribution over actions.
(the size of the first axis of `action_dist`)
Returns
----------
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Probability estimates of each arm being the best one for each sample, action, and position.
"""
action_dist = np.ones((n_rounds, self.n_actions, self.len_list)) * (
1 / self.n_actions
)
return action_dist
@dataclass
class BernoulliTS(BaseContextFreePolicy):
"""Bernoulli Thompson Sampling Policy
Parameters
----------
n_actions: int
Number of actions.
len_list: int, default=1
Length of a list of actions in a recommendation/ranking inferface, slate size.
When Open Bandit Dataset is used, 3 should be set.
batch_size: int, default=1
Number of samples used in a batch parameter update.
random_state: int, default=None
Controls the random seed in sampling actions.
alpha: array-like, shape (n_actions, ), default=None
Prior parameter vector for Beta distributions.
beta: array-like, shape (n_actions, ), default=None
Prior parameter vector for Beta distributions.
is_zozotown_prior: bool, default=False
Whether to use hyperparameters for the beta distribution used
at the start of the data collection period in ZOZOTOWN.
campaign: str, default=None
One of the three possible campaigns considered in ZOZOTOWN, "all", "men", and "women".
policy_name: str, default='bts'
Name of bandit policy.
"""
alpha: Optional[np.ndarray] = None
beta: Optional[np.ndarray] = None
is_zozotown_prior: bool = False
campaign: Optional[str] = None
policy_name: str = "bts"
def __post_init__(self) -> None:
"""Initialize class."""
super().__post_init__()
if self.is_zozotown_prior:
if self.campaign is None:
raise Exception(
"`campaign` must be specified when `is_zozotown_prior` is True."
)
self.alpha = production_prior_for_bts[self.campaign]["alpha"]
self.beta = production_prior_for_bts[self.campaign]["beta"]
else:
self.alpha = np.ones(self.n_actions) if self.alpha is None else self.alpha
self.beta = np.ones(self.n_actions) if self.beta is None else self.beta
def select_action(self) -> np.ndarray:
"""Select a list of actions.
Returns
----------
selected_actions: array-like, shape (len_list, )
List of selected actions.
"""
predicted_rewards = self.random_.beta(
a=self.reward_counts + self.alpha,
b=(self.action_counts - self.reward_counts) + self.beta,
)
return predicted_rewards.argsort()[::-1][: self.len_list]
def update_params(self, action: int, reward: float) -> None:
"""Update policy parameters.
Parameters
----------
action: int
Selected action by the policy.
reward: float
Observed reward for the chosen action and position.
"""
self.n_trial += 1
self.action_counts_temp[action] += 1
self.reward_counts_temp[action] += reward
if self.n_trial % self.batch_size == 0:
self.action_counts = np.copy(self.action_counts_temp)
self.reward_counts = np.copy(self.reward_counts_temp)
def compute_batch_action_dist(
self,
n_rounds: int = 1,
n_sim: int = 100000,
) -> np.ndarray:
"""Compute the distribution over actions by Monte Carlo simulation.
Parameters
----------
n_rounds: int, default=1
Number of rounds in the distribution over actions.
(the size of the first axis of `action_dist`)
n_sim: int, default=100000
Number of simulations in the Monte Carlo simulation to compute the distribution over actions.
Returns
----------
action_dist: array-like, shape (n_rounds, n_actions, len_list)
Probability estimates of each arm being the best one for each sample, action, and position.
"""
action_count = np.zeros((self.n_actions, self.len_list))
for _ in np.arange(n_sim):
selected_actions = self.select_action()
for pos in np.arange(self.len_list):
action_count[selected_actions[pos], pos] += 1
action_dist = np.tile(
action_count / n_sim,
(n_rounds, 1, 1),
)
return action_dist