forked from artiste-qb-net/Quantum_Edward
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFitter.py
More file actions
337 lines (271 loc) · 11.7 KB
/
Fitter.py
File metadata and controls
337 lines (271 loc) · 11.7 KB
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
335
336
337
import numpy as np
import numpy.random as npr
import scipy.stats as ss
import utilities as ut
from TimeStep import *
from Plotter import *
class Fitter:
"""
Read docstrings for Model class first.
The goal of this class is to implement the BBVI(see ref below) for a
Model object 'model' to estimate those values for the hidden variables
list1_angs which best fit the training data y_nsam_nb, x_nsam_na.
In BBVI, one maximizes ELBO with respect to a parameter lambda. In this
case, lambda = list1_conc0, list1_conc1 and z = list1_z =
list1_angs/dpi. The angles in list1_angs are in the interval [0, dpi] so
the entries list1_z are in the interval [0, 1].
References
----------
R. Ranganath, S. Gerrish, D. M. Blei, "Black Box Variational
Inference", https://arxiv.org/abs/1401.0118
"""
def __init__(self, model, y_nsam_nb, x_nsam_na, nsamgrad,
nt, eta, t_step_meth):
"""
Constructor
Parameters
----------
model : Model
y_nsam_nb : np.array
An array of zeros and ones with shape=(nsam, nb) containing nsam
samples of y output.
x_nsam_na : np.array
An array of zeros and ones with shape=(nsam, na) containing nsam
samples of x input.
nsamgrad : int
Number of samples used during averaging of the gradient of ELBO
nt : int
Number of time steps (aka iterations). Value of ELBO changes (
increases or stays the same) with each iteration.
eta : float
positive scaling parameter (proportionality factor) for delta
lambda. Passed to TimeStep class
t_step_meth : str
str labelling the method used to calculate delta lambda. This
str is passed to TimeStep class.
Returns
-------
None
"""
self.mod = model
self.y_nsam_nb = y_nsam_nb
self.x_nsam_na = x_nsam_na
self.nsamgrad = nsamgrad
self.nt = nt
self.eta = eta
self.t_step_meth = t_step_meth
assert self.mod.na == x_nsam_na.shape[1]
assert self.mod.nb == y_nsam_nb.shape[1]
assert self.y_nsam_nb.shape[0] == self.x_nsam_na.shape[0]
# the following will be filled by do_fit()
self.fin_t = None
self.fin_list1_conc0 = None
self.fin_list1_conc1 = None
len1 = self.mod.len1
self.conc_nt_2_len1 = np.zeros((nt, 2, len1), dtype=float)
self.delta_conc_nt_2_len1 = np.zeros((nt, 2, len1), dtype=float)
self.elbo_nt_len1 = np.zeros((nt, len1), dtype=float)
def get_delbo_and_grad_delbo(self, list1_z, list1_conc0, list1_conc1):
"""
delbo = density of elbo. grad = gradient. This is a private
auxiliary function used by do_fit(). Inside the method do_fit(),
we calculate elbo from delbo by taking expected value of delbo over
z~ q(z | lambda)
Parameters
----------
list1_z : list[np.array]
list1_conc0 : list[np.array]
list1_conc1 : list[np.array]
Returns
-------
tuple[list[np.array], list[np.array], list[np.array]]
"""
nsam = self.y_nsam_nb.shape[0]
len1 = self.mod.len1
# grad0,1 log q(z| lambda=conc0, conc1)
xx = [ut.grad_log_beta_prob(list1_z[k],
list1_conc0[k],
list1_conc1[k])
for k in range(len1)]
# zip doesn't work
# list1_g0, list1_g1 = zip(xx)
def my_zip(a):
return [[a[j][k] for j in range(len(a))]
for k in range(len(a[0]))]
# print('---------xx')
# for j in range(2):
# print(j, xx[j])
# print('---------zip(zz)')
# for j in range(2):
# tempo = list(zip(xx))
# print(j, tempo[j])
# print('---------my_zip(zz)')
# for j in range(2):
# tempo = my_zip(xx)
# print(j, tempo[j])
list1_g0, list1_g1 = my_zip(xx)
# sum_sam (log p(y| x, z = angs/dpi))
x_nsam = ut.bin_vec_to_dec(self.x_nsam_na, nsam=nsam)
y_nsam = ut.bin_vec_to_dec(self.y_nsam_nb, nsam=nsam)
list1_angs = [list1_z[k]*ut.dpi for k in range(len1)]
# log_py is a constant with shape 1
log_py = np.sum(np.log(1e-8 + np.array(
[self.mod.prob_y_given_x_and_angs_prior(y_nsam[sam],
x_nsam[sam], list1_angs) for sam in range(nsam)]
)))
# log_px is a constant with shape 1
log_px = np.sum(np.log(1e-8 + np.array(
[self.mod.prob_x(x_nsam[sam], list1_angs) for sam in range(nsam)]
)))
# log p(z)
list1_log_pz = [ut.log_beta_prob(list1_z[k],
self.mod.list1_conc0_prior[k],
self.mod.list1_conc1_prior[k])
for k in range(len1)]
# log q(z| lambda)
list1_log_qz = [ut.log_beta_prob(list1_z[k],
list1_conc0[k],
list1_conc1[k])
for k in range(len1)]
# log p(y, x, z) - log q(z | lambda)
list1_delbo = [log_py + log_px + list1_log_pz[k] - list1_log_qz[k]
for k in range(len1)]
# print("//", len1, "log_py=", log_py, list1_delbo)
list1_grad0_delbo = [np.multiply(list1_g0[k], list1_delbo[k])
for k in range(len1)]
list1_grad1_delbo = [np.multiply(list1_g1[k], list1_delbo[k])
for k in range(len1)]
return list1_delbo, list1_grad0_delbo, list1_grad1_delbo
def do_fit(self):
"""
This function attempts to maximize ELBO over lambda. Does at most nt
iterations (i.e., lambda changes, time steps). But may reach a
convergence condition before doing nt iterations. Final iteration
time is stored in self.fin_t.
This function stores final values for time and lambda (lambda =
concentrations 0, 1)
self.fin_t
self.fin_list1_conc0
self.fin_list1_conc1
It also stores traces (time series) for lambda (lambda =
concentrations 0, 1), delta lambda between consecutive steps,
and the ELBO value:
self.conc_nt_2_len1
self.delta_conc_nt_2_len1
self.elbo_nt_len1
Returns
-------
None
"""
len1 = self.mod.len1
# starting values
shapes = self.mod.shapes1
list1_conc0 = ut.new_uniform_array_list(1., shapes)
list1_conc1 = ut.new_uniform_array_list(1., shapes)
step = TimeStep(self.t_step_meth, self.eta, self.mod.len1)
for t in range(self.nt):
list1_elbo = ut.new_uniform_array_list(0., shapes)
list1_grad0_elbo = ut.new_uniform_array_list(0., shapes)
list1_grad1_elbo = ut.new_uniform_array_list(0., shapes)
for s in range(self.nsamgrad):
list1_z = [ss.beta.rvs(list1_conc0[k], list1_conc1[k])
for k in range(len1)]
x0, x1, x2 =\
self.get_delbo_and_grad_delbo(list1_z,
list1_conc0,
list1_conc1)
for k in range(len1):
list1_elbo[k] += x0[k]/self.nsamgrad
list1_grad0_elbo[k] += x1[k]/self.nsamgrad
list1_grad1_elbo[k] += x2[k]/self.nsamgrad
g0 = list1_grad0_elbo
g1 = list1_grad1_elbo
for k in range(len1):
delta_conc = step.get_delta_conc(g0[k], g1[k], t, k)
old_conc0 = np.copy(list1_conc0[k])
list1_conc0[k] += delta_conc[0]
list1_conc0[k] = np.clip(list1_conc0[k], 1e-5, 15)
true_delta_conc0 = list1_conc0[k] - old_conc0
old_conc1 = np.copy(list1_conc1[k])
list1_conc1[k] += delta_conc[1]
list1_conc1[k] = np.clip(list1_conc1[k], 1e-5, 15)
true_delta_conc1 = list1_conc1[k] - old_conc1
self.conc_nt_2_len1[t, 0, k] = np.sum(list1_conc0[k])
self.conc_nt_2_len1[t, 1, k] = np.sum(list1_conc1[k])
self.delta_conc_nt_2_len1[t, 0, k] = np.sum(true_delta_conc0)
self.delta_conc_nt_2_len1[t, 1, k] = np.sum(true_delta_conc1)
self.elbo_nt_len1[t, :] = \
ut.av_each_elem_in_array_list(list1_elbo)
if np.all(self.delta_conc_nt_2_len1[t, :, :] < 0.001):
break
self.fin_t = t
self.fin_list1_conc0 = list1_conc0
self.fin_list1_conc1 = list1_conc1
def print_fit_values_at_fin_t(self):
"""
Prints to screen summary of values at final time fin_t of do_fit()
run.
Recall z = ang/dpi with ang in interval [0, dpi] so z in interval [
0, 1].This function calculates for each z, its estimate, the std of
that estimate, and the fractional error (z_estimate -
z_prior)/z_prior. z_prior = angs_prior/dpi.
angs_prior are the prior angles assumed for the model. If we use
training data generated by Model:get_toy_data(), angs_prior are true
values, the ones used to generate the synthetic data.
Returns
-------
None
"""
len1 = self.mod.len1
list1_conc0 = self.fin_list1_conc0
list1_conc1 = self.fin_list1_conc1
list1_zpred = [ss.beta.mean(list1_conc0[k], list1_conc1[k])
for k in range(len1)]
list1_std_zpred = [ss.beta.std(list1_conc0[k], list1_conc1[k])
for k in range(len1)]
print('fin_t=', self.fin_t, "\n")
for k in range(len1):
print("list1_z[" + str(k) + "]:")
print("estimate:\n" + str(list1_zpred[k]))
print("st.dev.:\n" + str(list1_std_zpred[k]))
zprior = self.mod.list1_angs_prior[k]/ut.dpi
print("frac. error = (est-prior)/prior:\n" +
str((list1_zpred[k] - zprior)/zprior) + "\n")
def plot_fit_traces(self):
"""
Calls Plotter to plot traces (time series) collected during do_fit()
run. Plots time series of lambda, delta lambda and ELBO.
Returns
-------
None
"""
Plotter.plot_conc_traces(self.fin_t,
self.conc_nt_2_len1,
self.delta_conc_nt_2_len1)
Plotter.plot_elbo_traces(self.fin_t,
self.elbo_nt_len1)
if __name__ == "__main__":
from NbTrolsModel import *
from NoNbTrolsModel import *
def main():
# Ridiculously small numbers,
# just to make sure it runs without crashing
npr.seed(1234)
na = 2 # number of alpha qubits
nb = 2 # number of beta qubits
mod = NbTrolsModel(nb, na)
# mod = NoNbTrolsModel(nb, na)
nsam = 20 # number of samples
y_nsam_nb, x_nsam_na = mod.gen_toy_data(nsam)
nsamgrad = 10 # number of samples for grad estimate
nt = 20 # number of interations
# t_step_type, eta = naive', .0003 # very sensitive to eta
# t_step_type, eta = 'naive_t', .0003 # very sensitive to eta
# t_step_type, eta = 'mag1_grad', .2
t_step_meth, eta = 'ada_grad', .1
ff = Fitter(mod, y_nsam_nb, x_nsam_na,
nsamgrad, nt, eta, t_step_meth)
ff.do_fit()
ff.print_fit_values_at_fin_t()
ff.plot_fit_traces()
main()