-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmafs.py
602 lines (492 loc) · 24.4 KB
/
mafs.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import numpy as np
import numpy.random as rng
import tensorflow as tf
import mades
dtype = tf.float32
class BatchNormalization:
"""
Small implementation of Batch Normalization.
Mean and variance have to be updated manually.
"""
def __init__(self):
self.beta = None
self.loggamma = None
self.mean = None
self.variance = None
def __call__(self,input,training=False):
if self.loggamma == None:
self.initialize(input)
return self.apply(input,training=training)
def initialize(self,input):
n = int(input.shape[-1])
self.loggamma = tf.Variable(np.zeros(n),dtype=input.dtype,name='bn_loggamma')
self.beta = tf.Variable(np.zeros(n),dtype=input.dtype,name='bn_beta')
self.mean = tf.Variable(np.zeros(n),trainable=False,dtype=input.dtype,name='bn_mean')
self.variance = tf.Variable(np.ones(n),trainable=False,dtype=input.dtype,name='bn_variance')
self.variables = [self.loggamma,self.beta,self.mean,self.variance]
def apply(self,input,training=False):
momenta = tf.nn.moments(input,[0])
x_hat = tf.cond(training,
lambda: (input-momenta[0])/tf.sqrt(momenta[1]+1e-7),
lambda: (input-self.mean)/tf.sqrt(self.variance+1e-7))
output = tf.exp(self.loggamma)*x_hat+self.beta
return output
def eval_inv(self, sess, y):
"""
Evaluates the inverse batch norm transformation for output y.
:param y: output as numpy array
:return: input as numpy array
"""
loggamma,beta,mean,variance = sess.run(self.variables)
x_hat = (y - beta) / np.exp(loggamma)
x = np.sqrt(variance) * x_hat + mean
return x
class MaskedAutoregressiveFlow:
"""
Implements a Masked Autoregressive Flow, which is a stack of mades such that the random numbers which drive made i
are generated by made i-1. The first made is driven by standard gaussian noise. In the current implementation, all
mades are of the same type. If there is only one made in the stack, then it's equivalent to a single made.
"""
def __init__(self, n_inputs, n_hiddens, act_fun, n_mades, batch_norm=False,
input_order='sequential', mode='sequential', input=None):
"""
Constructor.
:param n_inputs: number of inputs
:param n_hiddens: list with number of hidden units for each hidden layer
:param act_fun: tensorflow activation function
:param n_mades: number of mades
:param batch_norm: whether to use batch normalization between mades
:param input_order: order of inputs of last made
:param mode: strategy for assigning degrees to hidden nodes: can be 'random' or 'sequential'
:param input: tensorflow placeholder to serve as input; if None, a new placeholder is created
"""
# save input arguments
self.n_inputs = n_inputs
self.n_hiddens = n_hiddens
self.act_fun = act_fun
self.n_mades = n_mades
self.batch_norm = batch_norm
self.momentum = momentum
self.mode = mode
self.input = tf.placeholder(dtype=dtype,shape=[None,n_inputs],name='x') if input is None else input
self.training = tf.placeholder_with_default(False,shape=(),name="training")
self.parms = []
self.mades = []
self.bns = []
self.moments = []
self.assign_bns = []
self.u = self.input
self.logdet_dudx = 0.0
for i in range(n_mades):
# create a new made
made = mades.GaussianMade(n_inputs, n_hiddens, act_fun, input_order, mode, self.u)
self.mades.append(made)
self.parms += made.parms
# invert input order
input_order = input_order if input_order == 'random' else made.input_order[::-1]
# inverse autoregressive transform
self.u = made.u
self.logdet_dudx += 0.5 * tf.reduce_sum(made.logp, axis=1,keepdims=True)
# batch normalization
if batch_norm:
bn = BatchNormalization()
moments = tf.nn.moments(self.u,[0])
v_tmp = moments[1]
self.u = bn(self.u,training=self.training)
self.parms += [bn.loggamma,bn.beta]
v_tmp = tf.cond(self.training,lambda:v_tmp,lambda:bn.variance)
self.logdet_dudx += tf.reduce_sum(bn.loggamma) - 0.5 * tf.reduce_sum(tf.log(v_tmp+1e-5))
self.bns.append(bn)
self.moments.append(moments)
self.assign_bns.append(tf.assign(bn.mean,moments[0]))
self.assign_bns.append(tf.assign(bn.variance,moments[1]))
self.input_order = self.mades[0].input_order
# log likelihoods
self.L = tf.add(-0.5 * n_inputs * np.log(2 * np.pi) - 0.5 * tf.reduce_sum(self.u ** 2, axis=1,keepdims=True),
self.logdet_dudx,name='L')
# train objective
self.trn_loss = -tf.reduce_mean(self.L,name='trn_loss')
def eval(self, x, sess, log=True, training=False):
"""
Evaluate log probabilities for given inputs.
:param x: data matrix where rows are inputs
:param sess: tensorflow session where the graph is run
:param log: whether to return probabilities in the log domain
:param training: in training, data mean and variance is used for batchnorm
while outside training the saved mean and variance is used
:return: list of log probabilities log p(x)
"""
lprob = sess.run(self.L,feed_dict={self.input:x,self.training:training})
return lprob if log else np.exp(lprob)
def update_batch_norm(self,x,sess):
"""
Updates batch normalization moments with the values obtained in data set x.
:param x: data matrix whose moments will be used for the update
:param sess: tensorflow session where the graph is run
:return: None
"""
sess.run(self.assign_bns,feed_dict={self.input:x,self.training:True})
def gen(self, sess, n_samples=1, u=None):
"""
Generate samples, by propagating random numbers through each made.
:param sess: tensorflow session where the graph is run
:param n_samples: number of samples
:param u: random numbers to use in generating samples; if None, new random numbers are drawn
:return: samples
"""
x = rng.randn(n_samples, self.n_inputs) if u is None else u
if getattr(self, 'batch_norm', False):
for made, bn in zip(self.mades[::-1], self.bns[::-1]):
x = bn.eval_inv(sess,x)
x = made.gen(sess,n_samples, x)
else:
for made in self.mades[::-1]:
x = made.gen(sess,n_samples, x)
return x
def calc_random_numbers(self, x, sess):
"""
Givan a dataset, calculate the random numbers used internally to generate the dataset.
:param x: numpy array, rows are datapoints
:param sess: tensorflow session where the graph is run
:return: numpy array, rows are corresponding random numbers
"""
return sess.run(self.u,feed_dict={self.input:x})
class WeightedMaskedAutoregressiveFlow:
"""
Implements a Masked Autoregressive Flow, which is a stack of mades such that the random numbers which drive made i
are generated by made i-1. The first made is driven by standard gaussian noise. In the current implementation, all
mades are of the same type. If there is only one made in the stack, then it's equivalent to a single made.
"""
def __init__(self, n_inputs, n_hiddens, act_fun, n_mades, batch_norm=False,
input_order='sequential', mode='sequential', input=None):
"""
Constructor.
:param n_inputs: number of inputs
:param n_hiddens: list with number of hidden units for each hidden layer
:param act_fun: tensorflow activation function
:param n_mades: number of mades
:param batch_norm: whether to use batch normalization between mades
:param input_order: order of inputs of last made
:param mode: strategy for assigning degrees to hidden nodes: can be 'random' or 'sequential'
:param input: tensorflow placeholder to serve as input; if None, a new placeholder is created
"""
# save input arguments
self.n_inputs = n_inputs
self.n_hiddens = n_hiddens
self.act_fun = act_fun
self.n_mades = n_mades
self.batch_norm = batch_norm
self.mode = mode
self.input = tf.placeholder(dtype=dtype,shape=[None,n_inputs],name='x') if input is None else input
self.weights = tf.placeholder(dtype=dtype,shape=[None,1],name='weights')
self.training = tf.placeholder_with_default(False,shape=(),name="training")
self.parms = []
self.mades = []
self.bns = []
self.moments = []
self.assign_bns = []
self.u = self.input
self.logdet_dudx = 0.0
for i in range(n_mades):
# create a new made
made = mades.GaussianMade(n_inputs, n_hiddens, act_fun, input_order, mode, self.u)
self.mades.append(made)
self.parms += made.parms
# invert input order
input_order = input_order if input_order == 'random' else made.input_order[::-1]
# inverse autoregressive transform
self.u = made.u
self.logdet_dudx += 0.5 * tf.reduce_sum(made.logp, axis=1,keepdims=True)
# batch normalization
if batch_norm:
bn = BatchNormalization()
moments = tf.nn.moments(self.u,[0])
v_tmp = moments[1]
self.u = bn(self.u,training=self.training)
self.parms += [bn.loggamma,bn.beta]
v_tmp = tf.cond(self.training,lambda:v_tmp,lambda:bn.variance)
self.logdet_dudx += tf.reduce_sum(bn.loggamma) - 0.5 * tf.reduce_sum(tf.log(v_tmp+1e-5))
self.bns.append(bn)
self.moments.append(moments)
self.assign_bns.append(tf.assign(bn.mean,moments[0]))
self.assign_bns.append(tf.assign(bn.variance,moments[1]))
self.input_order = self.mades[0].input_order
# log likelihoods
self.L = tf.add(-0.5 * n_inputs * np.log(2 * np.pi) - 0.5 * tf.reduce_sum(self.u ** 2, axis=1,keepdims=True),
self.logdet_dudx,name='L')
# train objective
self.trn_loss = -tf.divide(tf.reduce_sum(self.weights*self.L),tf.reduce_sum(self.weights),name='trn_loss')
def eval(self, x, sess, log=True, training=False):
"""
Evaluate log probabilities for given inputs.
:param x: data matrix where rows are inputs
:param sess: tensorflow session where the graph is run
:param log: whether to return probabilities in the log domain
:param training: in training, data mean and variance is used for batchnorm
while outside training the saved mean and variance is used
:return: list of log probabilities log p(x)
"""
lprob = sess.run(self.L,feed_dict={self.input:x,self.training:training})
return lprob if log else np.exp(lprob)
def update_batch_norm(self,x,sess):
"""
Updates batch normalization moments with the values obtained in data set x.
:param x: data matrix whose moments will be used for the update
:param sess: tensorflow session where the graph is run
:return: None
"""
sess.run(self.assign_bns,feed_dict={self.input:x,self.training:True})
def gen(self, sess, n_samples=1, u=None):
"""
Generate samples, by propagating random numbers through each made.
:param sess: tensorflow session where the graph is run
:param n_samples: number of samples
:param u: random numbers to use in generating samples; if None, new random numbers are drawn
:return: samples
"""
x = rng.randn(n_samples, self.n_inputs) if u is None else u
if getattr(self, 'batch_norm', False):
for made, bn in zip(self.mades[::-1], self.bns[::-1]):
x = bn.eval_inv(sess,x)
x = made.gen(sess,n_samples, x)
else:
for made in self.mades[::-1]:
x = made.gen(sess,n_samples, x)
return x
def calc_random_numbers(self, x, sess):
"""
Givan a dataset, calculate the random numbers used internally to generate the dataset.
:param x: numpy array, rows are datapoints
:param sess: tensorflow session where the graph is run
:return: numpy array, rows are corresponding random numbers
"""
return sess.run(self.u,feed_dict={self.input:x})
class ConditionalMaskedAutoregressiveFlow:
"""
Implements a Conditional Masked Autoregressive Flow.
"""
def __init__(self, n_inputs, n_outputs, n_hiddens, act_fun, n_mades, batch_norm=False,
output_order='sequential', mode='sequential', input=None, output=None):
"""
Constructor.
:param n_inputs: number of (conditional) inputs
:param n_outputs: number of outputs
:param n_hiddens: list with number of hidden units for each hidden layer
:param act_fun: tensorflow activation function
:param n_mades: number of mades in the flow
:param batch_norm: whether to use batch normalization between mades in the flow
:param output_order: order of outputs of last made
:param mode: strategy for assigning degrees to hidden nodes: can be 'random' or 'sequential'
:param input: tensorflow placeholder to serve as input; if None, a new placeholder is created
:param output: tensorflow placeholder to serve as output; if None, a new placeholder is created
"""
# save input arguments
self.n_inputs = n_inputs
self.n_outputs = n_outputs
self.n_hiddens = n_hiddens
self.act_fun = act_fun
self.n_mades = n_mades
self.batch_norm = batch_norm
self.mode = mode
self.input = tf.placeholder(dtype=dtype,shape=[None,n_inputs],name='x') if input is None else input
self.y = tf.placeholder(dtype=dtype,shape=[None,n_outputs],name='y') if output is None else output
self.training = tf.placeholder_with_default(False,shape=(),name="training")
self.parms = []
self.mades = []
self.bns = []
self.moments = []
self.assign_bns = []
self.u = self.y
self.logdet_dudy = 0.0
for i in range(n_mades):
# create a new made
made = mades.ConditionalGaussianMade(n_inputs, n_outputs, n_hiddens, act_fun,
output_order, mode, self.input, self.u)
self.mades.append(made)
self.parms += made.parms
output_order = output_order if output_order == 'random' else made.output_order[::-1]
# inverse autoregressive transform
self.u = made.u
self.logdet_dudy += 0.5 * tf.reduce_sum(made.logp, axis=1,keepdims=True)
# batch normalization
if batch_norm:
bn = BatchNormalization()
moments = tf.nn.moments(self.u,[0])
v_tmp = moments[1]
self.u = bn(self.u,training=self.training)
self.parms += [bn.loggamma,bn.beta]
v_tmp = tf.cond(self.training,lambda:v_tmp,lambda:bn.variance)
self.logdet_dudy += tf.reduce_sum(bn.loggamma) - 0.5 * tf.reduce_sum(tf.log(v_tmp+1e-5))
self.bns.append(bn)
self.moments.append(moments)
self.assign_bns.append(tf.assign(bn.mean,moments[0]))
self.assign_bns.append(tf.assign(bn.variance,moments[1]))
self.output_order = self.mades[0].output_order
# log likelihoods
self.L = tf.add(-0.5 * n_outputs * np.log(2 * np.pi) - 0.5 * tf.reduce_sum(self.u ** 2, axis=1,keepdims=True),
self.logdet_dudy,name='L')
# train objective
self.trn_loss = -tf.reduce_mean(self.L,name='trn_loss')
def eval(self, xy, sess, log=True, training=False):
"""
Evaluate log probabilities for given input-output pairs.
:param xy: a pair (x, y) where x rows are inputs and y rows are outputs
:param sess: tensorflow session where the graph is run
:param log: whether to return probabilities in the log domain
:param training: in training, data mean and variance is used for batchnorm
while outside training the saved mean and variance is used
:return: log probabilities: log p(y|x)
"""
x, y = xy
lprob = sess.run(self.L,feed_dict={self.input:x,self.y:y,self.training:training})
return lprob if log else np.exp(lprob)
def update_batch_norm(self,xy,sess):
"""
Updates batch normalization moments with the values obtained in data set x.
:param x: data matrix whose moments will be used for the update
:param sess: tensorflow session where the graph is run
:return: None
"""
x, y = xy
sess.run(self.assign_bns,feed_dict={self.input:x,self.y:y,self.training:True})
def gen(self, x, sess, n_samples=1, u=None):
"""
Generate samples, by propagating random numbers through each made, after conditioning on input x.
:param x: input vector
:param sess: tensorflow session where the graph is run
:param n_samples: number of samples
:param u: random numbers to use in generating samples; if None, new random numbers are drawn
:return: samples
"""
y = rng.randn(n_samples, self.n_outputs) if u is None else u
if getattr(self, 'batch_norm', False):
for made, bn in zip(self.mades[::-1], self.bns[::-1]):
y = bn.eval_inv(sess,y)
y = made.gen(x, sess, n_samples, y)
else:
for made in self.mades[::-1]:
y = made.gen(x, sess, n_samples, y)
return y
def calc_random_numbers(self, xy):
"""
Givan a dataset, calculate the random numbers used internally to generate the dataset.
:param xy: a pair (x, y) of numpy arrays, where x rows are inputs and y rows are outputs
:return: numpy array, rows are corresponding random numbers
"""
x, y = xy
return sess.run(self.u,feed_dict={self.input:x,self.y:y})
class WeightedConditionalMaskedAutoregressiveFlow:
"""
Implements a Conditional Masked Autoregressive Flow.
"""
def __init__(self, n_inputs, n_outputs, n_hiddens, act_fun, n_mades, batch_norm=False,
output_order='sequential', mode='sequential', input=None, output=None):
"""
Constructor.
:param n_inputs: number of (conditional) inputs
:param n_outputs: number of outputs
:param n_hiddens: list with number of hidden units for each hidden layer
:param act_fun: tensorflow activation function
:param n_mades: number of mades in the flow
:param batch_norm: whether to use batch normalization between mades in the flow
:param output_order: order of outputs of last made
:param mode: strategy for assigning degrees to hidden nodes: can be 'random' or 'sequential'
:param input: tensorflow placeholder to serve as input; if None, a new placeholder is created
:param output: tensorflow placeholder to serve as output; if None, a new placeholder is created
"""
# save input arguments
self.n_inputs = n_inputs
self.n_outputs = n_outputs
self.n_hiddens = n_hiddens
self.act_fun = act_fun
self.n_mades = n_mades
self.batch_norm = batch_norm
self.mode = mode
self.input = tf.placeholder(dtype=dtype,shape=[None,n_inputs],name='x') if input is None else input
self.weights = tf.placeholder(dtype=dtype,shape=[None,1],name='weights')
self.y = tf.placeholder(dtype=dtype,shape=[None,n_outputs],name='y') if output is None else output
self.training = tf.placeholder_with_default(False,shape=(),name="training")
self.parms = []
self.mades = []
self.bns = []
self.moments = []
self.assign_bns = []
self.u = self.y
self.logdet_dudy = 0.0
for i in range(n_mades):
# create a new made
made = mades.ConditionalGaussianMade(n_inputs, n_outputs, n_hiddens, act_fun,
output_order, mode, self.input, self.u)
self.mades.append(made)
self.parms += made.parms
output_order = output_order if output_order == 'random' else made.output_order[::-1]
# inverse autoregressive transform
self.u = made.u
self.logdet_dudy += 0.5 * tf.reduce_sum(made.logp, axis=1,keepdims=True)
# batch normalization
if batch_norm:
bn = BatchNormalization()
moments = tf.nn.moments(self.u,[0])
v_tmp = moments[1]
self.u = bn(self.u,training=self.training)
self.parms += [bn.loggamma,bn.beta]
v_tmp = tf.cond(self.training,lambda:v_tmp,lambda:bn.variance)
self.logdet_dudy += tf.reduce_sum(bn.loggamma) - 0.5 * tf.reduce_sum(tf.log(v_tmp+1e-5))
self.bns.append(bn)
self.moments.append(moments)
self.assign_bns.append(tf.assign(bn.mean,moments[0]))
self.assign_bns.append(tf.assign(bn.variance,moments[1]))
self.output_order = self.mades[0].output_order
# log likelihoods
self.L = tf.add(-0.5 * n_outputs * np.log(2 * np.pi) - 0.5 * tf.reduce_sum(self.u ** 2, axis=1,keepdims=True),
self.logdet_dudy,name='L')
# train objective
self.trn_loss = -tf.reduce_mean(self.weights*self.L,name='trn_loss')
def eval(self, xy, sess, log=True, training=False):
"""
Evaluate log probabilities for given input-output pairs.
:param xy: a pair (x, y) where x rows are inputs and y rows are outputs
:param sess: tensorflow session where the graph is run
:param log: whether to return probabilities in the log domain
:param training: in training, data mean and variance is used for batchnorm
while outside training the saved mean and variance is used
:return: log probabilities: log p(y|x)
"""
x, y = xy
lprob = sess.run(self.L,feed_dict={self.input:x,self.y:y,self.training:training})
return lprob if log else np.exp(lprob)
def update_batch_norm(self,xy,sess):
"""
Updates batch normalization moments with the values obtained in data set x.
:param x: data matrix whose moments will be used for the update
:param sess: tensorflow session where the graph is run
:return: None
"""
x, y = xy
sess.run(self.assign_bns,feed_dict={self.input:x,self.y:y,self.training:True})
def gen(self, x, sess, n_samples=1, u=None):
"""
Generate samples, by propagating random numbers through each made, after conditioning on input x.
:param x: input vector
:param sess: tensorflow session where the graph is run
:param n_samples: number of samples
:param u: random numbers to use in generating samples; if None, new random numbers are drawn
:return: samples
"""
y = rng.randn(n_samples, self.n_outputs) if u is None else u
if getattr(self, 'batch_norm', False):
for made, bn in zip(self.mades[::-1], self.bns[::-1]):
y = bn.eval_inv(sess,y)
y = made.gen(x, sess, n_samples, y)
else:
for made in self.mades[::-1]:
y = made.gen(x, sess, n_samples, y)
return y
def calc_random_numbers(self, xy):
"""
Givan a dataset, calculate the random numbers used internally to generate the dataset.
:param xy: a pair (x, y) of numpy arrays, where x rows are inputs and y rows are outputs
:return: numpy array, rows are corresponding random numbers
"""
x, y = xy
return sess.run(self.u,feed_dict={self.input:x,self.y:y})