-
Notifications
You must be signed in to change notification settings - Fork 8
/
vaessl_core.py
418 lines (318 loc) · 14.9 KB
/
vaessl_core.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
"""
Code implementing inference and generative models for semi-supervised
variational autoencoder (VAE-SSL) approach to source localization in reverberant
environments
The method implemented here is described in:
1. M.J. Bianco, S. Gannot, E. Fernandez-Grande, P. Gerstoft, "Semi-supervised
source localization in reverberant environments," IEEE Access, Vol. 9, 2021.
DOI: 10.1109/ACCESS.2021.3087697
The code is based on the Pyro probabilistic programming library and Pytorch.
Copyright (c) 2017-2019 Uber Technologies, Inc.
SPDX-License-Identifier: Apache-2.0
2. E. Bingham et al., "Pyro: Deep Universal Probabilistic Programming,"
Journal of Machine Learning Research, 2018.
3. A. Paszke et al., "Pytorch: An imperative style, high-performance deep
learning library," Proc. Adv. Neural Inf. Process. Syst., 2019, pp. 8024–8035.
If you find this code usefult for your research, please cite (1)--(3).
Michael J. Bianco, July 2021
"""
import argparse
import torch
import torch.nn as nn
import numpy as np
import pyro
import pyro.distributions as dist
from pyro.infer import config_enumerate
from pyro.optim import Adam
from utils.networks import CNN_yx,CNN_zxy,CNN_xyz
import utils.data_cls as data_cls
class TruncatedNormal(dist.Rejector):
def __init__(self, loc, scale,cuda_id):
lim = 1.0
min_x = torch.tensor(np.array([-lim]).astype('float32'))
max_x = torch.tensor(np.array([lim]).astype('float32'))
if cuda_id is not None:
min_x = min_x.cuda(cuda_id)
max_x = max_x.cuda(cuda_id)
propose = dist.Normal(loc, scale)
def log_prob_accept(x): # gives log acceptance (0 if outside, and 1 if inside truncated Gaussian)
thresh_min = x >= min_x
thresh_max = x <= max_x
return (thresh_min*thresh_max).type_as(x).log() # logical multiplcation, same as 'and'
cdf_min = dist.Normal(loc, scale).cdf(min_x)
cdf_max = dist.Normal(loc, scale).cdf(max_x)
log_scale = torch.log(cdf_max-cdf_min) # log total probability of acceptance
super(TruncatedNormal, self).__init__(propose, log_prob_accept, log_scale)
class SSVAE(nn.Module):
"""
This class encapsulates the parameters (neural networks) and models & guides needed to train a
semi-supervised variational auto-encoder to generate RTF-phase sequences and localize acoustic sources
:param output_size: size of the tensor representing the DOA
:param input_size: size of the tensor representing the RTF-phase sequence
:param z_dim: size of the tensor representing the latent random variable z
:param use_cuda: use GPUs for faster training
:param aux_loss_multiplier: the multiplier to use with the auxiliary loss
"""
def __init__(self, output_size=10, input_size=(31,127), z_dim=50,
config_enum=None, aux_loss_multiplier=None, batch_size=256, cuda_id=None):
super().__init__()
use_cuda = False
if cuda_id is not None: use_cuda = True
# print(use_cuda, cuda_id)
self.output_size = output_size
self.input_size = input_size
self.z_dim = z_dim
self.allow_broadcast = config_enum == 'parallel'
self.use_cuda = use_cuda
self.aux_loss_multiplier = aux_loss_multiplier
self.batch_size = batch_size
self.cuda_id = cuda_id
self.num_classes = output_size
# define and instantiate the neural networks representing
# the paramters of various distributions in the model
self.setup_networks()
def setup_networks(self):
z_dim = self.z_dim
self.encoder_y = CNN_yx(use_cuda=self.use_cuda,y_size=self.output_size,cuda_id=self.cuda_id, x_size=self.input_size)
self.encoder_z = CNN_zxy(use_cuda=self.use_cuda,y_size=self.output_size,z_dim=self.z_dim,cuda_id=self.cuda_id, x_size=self.input_size)
self.decoder = CNN_xyz(use_cuda=self.use_cuda,y_size=self.output_size,z_dim=self.z_dim,cuda_id=self.cuda_id, x_size=self.input_size)
# using GPUs for faster training of the networks
if self.use_cuda:
self.cuda(self.cuda_id)
def model(self, xs, ys=None, **kwargs):
"""
The model corresponds to the following generative process:
p(z) = normal(0,I) # latent variable, factors generating RTF unrelated to source DOA
p(y|x) = categorical(I/10.) # which DOA (semi-supervised)
p(x|y,z) = bernoulli(loc(y,z)) # RTF-phase sequence
loc is given by a neural network `decoder`
:param xs: a batch of RTF-phase sequences
:param ys: (optional) a batch of the DOA labels, corresponding to input RTF-phase sequence
:return: None
"""
# register this pytorch module and all of its sub-modules with pyro
pyro.module("ss_vae", self)
batch_size = xs.size(0)
options = dict(dtype=xs.dtype, device=xs.device)
with pyro.plate("data"):
# sample the latent variable from the constant prior distribution
prior_loc = torch.zeros(batch_size, self.z_dim, **options)
prior_scale = torch.ones(batch_size, self.z_dim, **options)
zs = pyro.sample("z", dist.Normal(prior_loc, prior_scale).to_event(1))
alpha_prior = torch.ones(batch_size, self.output_size, **options) / (1.0 * self.output_size)
ys = pyro.sample("y", dist.OneHotCategorical(alpha_prior), obs=ys)
x_loc, x_scale = self.decoder.forward([zs, ys])
pyro.sample("x", TruncatedNormal(x_loc,x_scale,self.cuda_id).to_event(1), obs=xs)
def guide(self, xs, ys=None, **kwargs):
"""
The guide corresponds to the following:
q(y|x) = categorical(alpha(x)) # infer DOA from an RTF-phase sequence
q(z|x,y) = normal(loc(x,y),scale(x,y)) # obtain latent value corresponding to an RTF-phase sequence and DOA
loc, scale are given by a neural network `encoder_z`
alpha is given by a neural network `encoder_y`
:param xs: a batch of RTF-phase sequences
:param ys: (optional) a batch of the DOA labels, corresponding to input RTF-phase sequence
:return: None
"""
self.encoder_y.train() # ensuring that network is trained (vs. eval)
with pyro.plate("data"):
# if the class label is not supervised, sample
# (and score) the RTF-phase sequence with the variational distribution
# q(y|x) = categorical(alpha(x))
if ys is None:
alpha = self.encoder_y.forward(xs)
ys = pyro.sample("y", dist.OneHotCategorical(alpha))
loc, scale = self.encoder_z.forward([xs, ys])
pyro.sample("z", dist.Normal(loc, scale).to_event(1))
def classifier(self, xs, eval = False):
"""
estimate DOA from RTF-phase sequence
:param xs: a batch of RTF-phase sequences
:return: a batch of the corresponding DOAs (as one-hot encoding)
"""
# use the trained model q(y|x) = categorical(alpha(x))
# compute all class probabilities for RTF-sequence(s)
if eval == True:
self.encoder_y.eval()
else:
self.encoder_y.train()
alpha = self.encoder_y.forward(xs)
# get the index (DOA) that corresponds to
# the maximum predicted class probability
res, ind = torch.topk(alpha, 1)
# convert the indices to one-hot tensor(s)
ys = torch.zeros_like(alpha).scatter_(1, ind, 1.0)
return ys
def model_classify(self, xs, ys=None, **kwargs):
"""
this model is used to add an auxiliary (supervised) loss as described in the
Kingma et al., "Semi-Supervised Learning with Deep Generative Models".
"""
# register all pytorch (sub)modules with pyro
pyro.module("ss_vae", self)
self.encoder_y.train()
# inform Pyro that the variables in the batch of xs, ys are conditionally independent
with pyro.plate("data"):
# this here is the extra term to yield an auxiliary loss that we do gradient descent on
if ys is not None:
alpha = self.encoder_y.forward(xs)
with pyro.poutine.scale(scale=self.aux_loss_multiplier):
pyro.sample("y_aux", dist.OneHotCategorical(alpha), obs=ys)
def guide_classify(self, xs, ys=None, **kwargs):
"""
dummy guide function to accompany model_classify in inference
"""
pass
def reconstruct_img2(self, xs, ys):
# encode RTF-phase sequence x
z_loc, z_scale = self.encoder_z([xs, ys])
# sample in latent space
zs = dist.Normal(z_loc, z_scale).sample()
# decode the RTF-phase sequence
x_loc,x_scale = self.decoder([zs,ys])
xr = TruncatedNormal(x_loc,x_scale,self.cuda_id).sample()
return xr, zs, x_loc, x_scale
def cond_sample(self, ys):
# sample from p(z)
ys = ys.unsqueeze(0) # adding singleton dimension to interface with CNNs
prior_loc = torch.zeros(ys.shape[-2], self.z_dim)
prior_scale = torch.ones(ys.shape[-2], self.z_dim)
# sample in latent space
zs = dist.Normal(prior_loc,prior_scale).sample()
zs = zs.cuda(self.cuda_id)
# decode the RTF-phase sequence
x_loc,x_scale = self.decoder([zs,ys])
xr = TruncatedNormal(x_loc,x_scale,self.cuda_id).sample()
return xr, zs, x_loc, x_scale
def run_inference_for_epoch(data_loaders, losses, periodic_interval_batches):
"""
runs the inference algorithm for an epoch
returns the values of all losses separately on supervised and unsupervised parts
"""
num_losses = len(losses)
# compute number of batches for an epoch
sup_batches = len(data_loaders["sup"])
unsup_batches = len(data_loaders["unsup"])
batches_per_epoch = sup_batches + unsup_batches
# initialize variables to store loss values
epoch_losses_sup = [0.] * num_losses
epoch_losses_unsup = [0.] * num_losses
# setup the iterators for training data loaders
sup_iter = iter(data_loaders["sup"])
unsup_iter = iter(data_loaders["unsup"])
# count the number of supervised batches seen in this epoch
ctr_sup = 0
for i in range(batches_per_epoch):
# whether this batch is supervised or not
is_supervised = (i % periodic_interval_batches == 1) and ctr_sup < sup_batches
# extract the corresponding batch
if is_supervised:
(xs, ys) = next(sup_iter)
ctr_sup += 1
else:
(xs, ys) = next(unsup_iter)
# run the inference for each loss with supervised or un-supervised
# data as arguments
for loss_id in range(num_losses):
if is_supervised:
new_loss = losses[loss_id].step(xs, ys)
epoch_losses_sup[loss_id] += new_loss
else:
new_loss = losses[loss_id].step(xs)
epoch_losses_unsup[loss_id] += new_loss
return epoch_losses_sup, epoch_losses_unsup
def get_loss_for_epoch(data_loaders, losses, periodic_interval_batches):
"""
runs the inference algorithm for an epoch
returns the values of all losses separately on supervised and unsupervised parts
"""
num_losses = len(losses)
# compute number of batches for an epoch
sup_batches = len(data_loaders["sup"])
unsup_batches = len(data_loaders["unsup"])
batches_per_epoch = sup_batches + unsup_batches
# initialize variables to store loss values
epoch_losses_sup = [0.] * num_losses
epoch_losses_unsup = [0.] * num_losses
# setup the iterators for training data loaders
sup_iter = iter(data_loaders["sup"])
unsup_iter = iter(data_loaders["unsup"])
# count the number of supervised batches seen in this epoch
ctr_sup = 0
for i in range(batches_per_epoch):
# whether this batch is supervised or not
is_supervised = (i % periodic_interval_batches == 1) and ctr_sup < sup_batches
# extract the corresponding batch
if is_supervised:
(xs, ys) = next(sup_iter)
ctr_sup += 1
for loss_id in range(num_losses):
if is_supervised:
new_loss = losses[loss_id].evaluate_loss(xs, ys)
epoch_losses_sup[loss_id] += new_loss
# return the values of all losses
return epoch_losses_sup
def get_accuracy(data_loader, classifier_fn, num_classes):
"""
compute the accuracy over the supervised training set or the testing set
"""
predictions, actuals = [], []
numCases = 0
# use the appropriate data loader
for (xs, ys) in data_loader:
# use classification function to compute all predictions for each batch
predictions.append(classifier_fn(xs,eval=True)) # eval to suspend dropout sampling in trained network
actuals.append(ys)
# compute the number of accurate predictions
accurate_preds = 0
for pred, act in zip(predictions, actuals):
for i in range(pred.size(0)): # for each case from the batch
v = torch.sum(pred[i] == act[i]) # matching classes
accurate_preds += (v.item() == num_classes)
numCases += 1
# calculate the accuracy between 0 and 1
accuracy = (accurate_preds * 1.0) / numCases
return accuracy
def get_mae(data_loader, vae_model, classes):
"""
compute the doa mae over the supervised training set or the testing set
"""
predictions, actuals = [], []
error=0
nData=0
vae_model.eval() # eval to suspend dropout sampling in trained network
for i, data in enumerate(data_loader, 0):
pred = vae_model(data[0])
estInds = pred.argmax(axis=1)
trueInds = data[1].argmax(axis=1)
estDOAs = classes[estInds]
predictions.extend(estDOAs.detach().cpu().flatten().tolist())
trueDOAs= classes[trueInds]
actuals.extend(trueDOAs.detach().cpu().flatten().tolist())
error += torch.sum(torch.abs(estDOAs-trueDOAs))
nData += len(trueDOAs)
mae = error/nData
return mae, [predictions,actuals]
def get_mae_off(data_loader, vae_model, classes_dict):
"""
off-grid/ off-range processing compute the doa mae over the supervised training set or the testing set
"""
predictions, actuals = [], []
error=0
nData=0
classes = classes_dict['model']
classes_off = classes_dict['off grid']
vae_model.eval() # eval to suspend dropout sampling in trained network
loader_keys = ["sup","test"] # using both sup and test for calculating error
for k in loader_keys:
for i, data in enumerate(data_loader[k], 0):
pred = vae_model(data[0])
estInds = pred.argmax(axis=1)
estDOAs = classes[estInds]
trueInds = data[1].argmax(axis=1)
trueDOAs= classes_off[trueInds]
error += torch.sum(torch.abs(estDOAs-trueDOAs))
nData += len(trueDOAs)
mae = error/nData
return mae