-
Notifications
You must be signed in to change notification settings - Fork 0
/
DPclass.py
334 lines (270 loc) · 10.6 KB
/
DPclass.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
331
332
333
334
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
class ucb_bandit:
'''
Upper Confidence Bound Bandit (with DP)
Inputs
============================================
k: number of arms (int)
iters: number of steps (int)
mu: average rewards for each of the k-arms.
epsilon: parameter of DP
type: DP mechanism (e.g., Laplace or Bernoulli)
'''
def __init__(self, k, iters, mu, epsilon = 0, type = None):
# Number of arms
self.k = k
# Number of iterations
self.iters = iters
# Step count
self.n = 1
# Step count for each arm
self.k_n = np.ones(k)
# Total regret
self.total_regret = 0
self.regret = np.zeros(iters)
# Empirical reward for each arm
self.k_reward = np.zeros(k)
# Privacy parameter
self.epsilon = epsilon
# Average reward for each arm
self.mu = np.array(mu)
# DP type
self.type = type
def generate_reward(self, mu):
return np.random.binomial(1,mu,1)
# Naive UCB
def pull(self):
# Select action according to UCB Criteria
a = np.argmax(self.k_reward + np.sqrt(
(2*np.log(self.n)) / self.k_n))
reward = self.generate_reward(self.mu[a])
optimal_reward = self.generate_reward(self.mu[0])
# Update counts
self.n += 1
self.k_n[a] += 1
# Update total
self.total_regret = self.total_regret + optimal_reward - reward
# Update results for a_k
self.k_reward[a] = self.k_reward[a] + (
reward - self.k_reward[a]) / self.k_n[a]
# LDP-UCB-B
def pull_CTB(self):
# Select action according to the Criteria
a = np.argmax(self.k_reward + np.sqrt(
(2*np.log(self.n)) / self.k_n))
reward = self.generate_reward(self.mu[a])
optimal_reward = self.generate_reward(self.mu[0])
# Update total
self.total_regret = self.total_regret + optimal_reward - reward
# Update counts
self.n += 1
self.k_n[a] += 1
# Using Bernoulli mechanism
mu_converted = (reward*np.exp(self.epsilon)+1-reward )/(1+np.exp(self.epsilon))
reward_converted = np.random.binomial(1,mu_converted,1)
# Update results for a_k
self.k_reward[a] = self.k_reward[a] + (
reward_converted - self.k_reward[a]) / self.k_n[a]
# LDP-UCB-L
def pull_CTL(self):
# Select action according to the Criteria
th = 4 * np.log(self.n + 1) # threshold
k_n_th = [(i,el) for (i,el) in enumerate(self.k_n) if el <= th]
if len(k_n_th) > 0:
a = k_n_th[0][0]
else:
a = np.argmax(self.k_reward + np.sqrt(
(2*np.log(self.n)) / self.k_n) + np.sqrt(
(32*np.log(self.n) / (self.epsilon * self.epsilon * self.k_n))))
reward = self.generate_reward(self.mu[a])
optimal_reward = self.generate_reward(self.mu[0])
# Update total
self.total_regret = self.total_regret + optimal_reward - reward
# Update counts
self.n += 1
self.k_n[a] += 1
# Using Laplace mechanism
reward_converted = reward + np.random.laplace(0,1/self.epsilon,1)
# Update results for a_k
self.k_reward[a] = self.k_reward[a] + (
reward_converted - self.k_reward[a]) / self.k_n[a]
def run(self):
for i in range(self.iters):
if self.type == 'Laplace':
self.pull_CTL()
elif self.type == 'Bernoulli':
self.pull_CTB()
else:
self.pull()
self.regret[i] = self.total_regret
def reset(self):
# Resets results while keeping settings
self.n = 1
self.k_n = np.ones(self.k)
self.total_regret = 0
self.regret = np.zeros(self.iters)
self.k_reward = np.zeros(self.k)
class ucb_bandit_heter(ucb_bandit):
def generate_reward(self, mu):
'''
mu = 0.9: Bernoulli
mu = 0.8: Beta(4,1)
mu = 0.7: randomly choose [0.4, 1] with prob [0.5, 0.5]
mu = 0.6: Bernoulli
mu = 0.5: Uniform in [0,1]
'''
if mu == 0.9:
return np.random.binomial(1,mu,1)
if mu == 0.8:
return np.random.beta(4,1,1)
if mu == 0.7:
return np.random.choice([0.4, 1], 1, p=[0.5, 0.5])
if mu == 0.6:
return np.random.binomial(1,mu,1)
if mu == 0.5:
return np.random.uniform(0,1,1)
class ucb_bandit_gaussian(ucb_bandit):
def generate_reward(self, mu):
sigma = 1
return np.random.normal(mu,sigma,1)
# Using Sigmoid
def pull(self):
# Select action according to UCB Criteria
a = np.argmax(self.k_reward + np.sqrt(
(2*np.log(self.n)) / self.k_n))
reward = self.generate_reward(self.mu[a])
optimal_reward = self.generate_reward(self.mu[0])
# Update counts
self.n += 1
self.k_n[a] += 1
# Update total
self.total_regret = self.total_regret + optimal_reward - reward
sr = 1/(1+np.exp(-reward))
# Update results for a_k
self.k_reward[a] = self.k_reward[a] + (
sr - self.k_reward[a]) / self.k_n[a]
# Using Sigmoid
def pull_CTB(self):
# Select action according to the Criteria
a = np.argmax(self.k_reward + np.sqrt(
(2*np.log(self.n)) / self.k_n))
reward = self.generate_reward(self.mu[a])
optimal_reward = self.generate_reward(self.mu[0])
# Update total
self.total_regret = self.total_regret + optimal_reward - reward
# Update counts
self.n += 1
self.k_n[a] += 1
# Using Sigmoid-Bernoulli mechanism
sr = 1/(1+np.exp(-reward))
mu_converted = (sr*np.exp(self.epsilon)+1-sr )/(1+np.exp(self.epsilon))
reward_converted = np.random.binomial(1,mu_converted,1)
# Update results for a_k
self.k_reward[a] = self.k_reward[a] + (
reward_converted - self.k_reward[a]) / self.k_n[a]
# Using Sigmoid
def pull_CTL(self):
# Select action according to the Criteria
th = 4 * np.log(self.n + 1) # threshold
k_n_th = [(i,el) for (i,el) in enumerate(self.k_n) if el <= th]
if len(k_n_th) > 0:
a = k_n_th[0][0]
else:
a = np.argmax(self.k_reward + np.sqrt(
(2*np.log(self.n)) / self.k_n) + np.sqrt(
(32*np.log(self.n) / (self.epsilon * self.epsilon * self.k_n))))
reward = self.generate_reward(self.mu[a])
optimal_reward = self.generate_reward(self.mu[0])
# Update total
self.total_regret = self.total_regret + optimal_reward - reward
# Update counts
self.n += 1
self.k_n[a] += 1
# Using Sigmoid-Laplace mechanism
sr = 1/(1+np.exp(-reward))
reward_converted = sr + np.random.laplace(0,1/self.epsilon,1)
# Update results for a_k
self.k_reward[a] = self.k_reward[a] + (
reward_converted - self.k_reward[a]) / self.k_n[a]
def experiment_with_algorithms(k, mu, epsilon, type_list, reward_type = 'Bern', iters=100000, episodes=100):
UCB_list = []
for i in range(len(type_list)):
if reward_type == 'Bern':
UCB_list.append(ucb_bandit(k,iters, mu, epsilon, type_list[i]))
elif reward_type == 'Mixed':
UCB_list.append(ucb_bandit_heter(k,iters, mu, epsilon, type_list[i]))
elif reward_type == 'Gaussian':
UCB_list.append(ucb_bandit_gaussian(k,iters, mu, epsilon, type_list[i]))
Regrets_list = []
for _ in range(len(type_list)):
Regrets_list.append(np.zeros(iters))
for j in range(len(type_list)):
for i in range(episodes):
UCB_list[j].reset()
UCB_list[j].run()
Regrets_list[j] = Regrets_list[j] + (
UCB_list[j].regret - Regrets_list[j]) / (i + 1)
return Regrets_list
def experiment_with_epsilon(k, mu, epsilon_list, type, reward_type = 'Bern', iters=100000, episodes=100):
UCB_list = []
for i in range(len(epsilon_list)):
if reward_type == 'Bern':
UCB_list.append(ucb_bandit(k,iters, mu, epsilon_list[i],type))
elif reward_type == 'Mixed':
UCB_list.append(ucb_bandit_heter(k,iters, mu, epsilon_list[i],type))
elif reward_type == 'Gaussian':
UCB_list.append(ucb_bandit_gaussian(k,iters, mu, epsilon_list[i],type))
Regrets_list = []
for _ in range(len(epsilon_list)):
Regrets_list.append(np.zeros(iters))
for j in range(len(epsilon_list)):
for i in range(episodes):
UCB_list[j].reset()
UCB_list[j].run()
Regrets_list[j] = Regrets_list[j] + (
UCB_list[j].regret - Regrets_list[j]) / (i + 1)
return Regrets_list
def plot_algorithms(type_list, regrets_algorithms, iters):
fig = plt.figure()
ax = fig.gca()
for i in range(len(type_list)):
type = type_list[i] if type_list[i] is not None else 'UCB'
if type == 'Bernoulli':
label = 'LDP-UCB-B'
elif type == 'Laplace':
label = 'LDP-UCB-L'
else:
label = 'Non-Private-UCB'
ax.plot(regrets_algorithms[i], label=label )
plt.yscale('log')
plt.xscale('log')
plt.xlabel("T")
plt.ylabel("Regret")
plt.axis([100, iters, 1, 100000])
plt.grid('True',linestyle = '--')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.rcParams.update({'font.size': 16})
#plt.ticklabel_format(style='sci', axis='x',scilimits=(5,5))
ax.legend(loc='lower right', frameon=False)
plt.show()
def plot_epsilon(epsilon_list,regrets_epsilon, iters):
fig = plt.figure()
ax = fig.gca()
for i in range(len(epsilon_list)):
ep = epsilon_list[i]
ax.plot(regrets_epsilon[i], label=r'$\epsilon = $'+str(ep) )
plt.yscale('log')
plt.xscale('log')
plt.xlabel("T")
plt.ylabel("Regret")
plt.axis([100, iters, 1, 100000])
plt.grid('True',linestyle = '--')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.rcParams.update({'font.size': 16})
#plt.ticklabel_format(style='sci', axis='x',scilimits=(4,4))
ax.legend(loc='lower right', frameon=False)
plt.show()