-
Notifications
You must be signed in to change notification settings - Fork 4
/
scholar.py
executable file
·1304 lines (1089 loc) · 59.9 KB
/
scholar.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.init import xavier_uniform_
import copy
class Scholar(object):
def __init__(self, config, alpha=1.0, learning_rate=0.001, init_embeddings=None, update_embeddings=True,
init_bg=None, update_background=True, adam_beta1=0.99, adam_beta2=0.999, device=None, seed=None,
classify_from_covars=True, model='scholar', topk=1):
"""
Create the model
:param config: a dictionary with the model configuration
:param alpha: hyperparameter for the document representation prior
:param learning_rate: learning rate for Adam
:param init_embeddings: a matrix of embeddings to initialize the first layer of the bag-of-words encoder
:param update_embeddings: if True, update word embeddings during training
:param init_bg: a vector of empirical log backgound frequencies
:param update_background: if True, update the background term during training
:param adam_beta1: first hyperparameter for Adam
:param adam_beta2: second hyperparameter for Adam
:param device: (int) the number of the GPU to use
"""
if seed is not None:
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
self.network_architecture = config
self.learning_rate = learning_rate
self.adam_beta1 = adam_beta1
self.update_embeddings = update_embeddings
self.update_background = update_background
# create priors on the hidden state
self.n_topics = (config["n_topics"])
if device is None:
self.device = 'cpu'
else:
self.device = 'cuda:' + str(device)
# interpret alpha as either a (symmetric) scalar prior or a vector prior
if np.array(alpha).size == 1:
# if alpha is a scalar, create a symmetric prior vector
self.alpha = alpha * np.ones((1, self.n_topics)).astype(np.float32)
else:
# otherwise use the prior as given
self.alpha = np.array(alpha).astype(np.float32)
assert len(self.alpha) == self.n_topics
# create the pyTorch model
if model == 'scholar':
self._model = torchScholar(config, self.alpha, update_embeddings, init_emb=init_embeddings, bg_init=init_bg, device=self.device, classify_from_covars=classify_from_covars).to(self.device)
elif model == 'contrastiveScholar':
self._model = torchContrastiveScholar(config, self.alpha, update_embeddings, init_emb=init_embeddings, bg_init=init_bg, device=self.device, classify_from_covars=classify_from_covars,topk=topk).to(self.device)
elif model == 'trueContrastiveScholar':
self._model = torchTrueContrastiveScholar(config, self.alpha, update_embeddings, init_emb=init_embeddings, bg_init=init_bg, device=self.device, classify_from_covars=classify_from_covars,topk=topk).to(self.device)
# set the criterion
self.criterion = nn.BCEWithLogitsLoss()
# create the optimizer
grad_params = filter(lambda p: p.requires_grad, self._model.parameters())
self.optimizer = optim.Adam(grad_params, lr=learning_rate, betas=(adam_beta1, adam_beta2))
def fit(self, X, Y, PC, TC, eta_bn_prop=1.0, l1_beta=None, l1_beta_c=None, l1_beta_ci=None):
"""
Fit the model to a minibatch of data
:param X: np.array of document word counts [batch size x vocab size]
:param Y: np.array of labels [batch size x n_labels]
:param PC: np.array of prior covariates influencing the document-topic prior [batch size x n_prior_covars]
:param TC: np.array of topic covariates to be associated with topical deviations [batch size x n_topic_covars]
:param l1_beta: np.array of prior variances on the topic weights
:param l1_beta_c: np.array of prior variances on the weights for topic covariates
:param l1_beta_ci: np.array of prior variances on the weights for topic-covariate interactions
:return: loss; label pred probs; document representations; neg-log-likelihood; KLD
"""
# move data to device
X = torch.Tensor(X).to(self.device)
if Y is not None:
Y = torch.Tensor(Y).to(self.device)
if PC is not None:
PC = torch.Tensor(PC).to(self.device)
if TC is not None:
TC = torch.Tensor(TC).to(self.device)
self.optimizer.zero_grad()
# do a forward pass
thetas, X_recon, Y_probs, losses = self._model(X, Y, PC, TC, eta_bn_prop=eta_bn_prop, l1_beta=l1_beta, l1_beta_c=l1_beta_c, l1_beta_ci=l1_beta_ci)
loss, nl, kld = losses
# update model
loss.backward()
self.optimizer.step()
if Y_probs is not None:
Y_probs = Y_probs.to('cpu').detach().numpy()
return loss.to('cpu').detach().numpy(), Y_probs, thetas.to('cpu').detach().numpy(), nl.to('cpu').detach().numpy(), kld.to('cpu').detach().numpy()
def predict(self, X, PC, TC, eta_bn_prop=0.0):
"""
Predict labels for a minibatch of data
"""
# input a vector of all zeros in place of the labels that the model has been trained on
batch_size = self.get_batch_size(X)
Y = np.zeros((batch_size, self.network_architecture['n_labels'])).astype('float32')
X = torch.Tensor(X).to(self.device)
Y = torch.Tensor(Y).to(self.device)
if PC is not None:
PC = torch.Tensor(PC).to(self.device)
if TC is not None:
TC = torch.Tensor(TC).to(self.device)
theta, _, Y_recon, _ = self._model(X, Y, PC, TC, do_average=False, var_scale=0.0, eta_bn_prop=eta_bn_prop)
return theta, Y_recon.to('cpu').detach().numpy()
def predict_from_topics(self, theta, PC, TC, eta_bn_prop=0.0):
"""
Predict label probabilities from each topic
"""
theta = torch.Tensor(theta)
if PC is not None:
PC = torch.Tensor(PC)
if TC is not None:
TC = torch.Tensor(TC)
probs = self._model.predict_from_theta(theta, PC, TC)
return probs.to('cpu').detach().numpy()
def get_losses(self, X, Y, PC, TC, eta_bn_prop=0.0, n_samples=0):
"""
Compute and return the loss values for all instances in X, Y, PC, and TC averaged over multiple samples
"""
batch_size = self.get_batch_size(X)
if batch_size == 1:
X = np.expand_dims(X, axis=0)
if Y is not None and batch_size == 1:
Y = np.expand_dims(Y, axis=0)
if PC is not None and batch_size == 1:
PC = np.expand_dims(PC, axis=0)
if TC is not None and batch_size == 1:
TC = np.expand_dims(TC, axis=0)
X = torch.Tensor(X).to(self.device)
if Y is not None:
Y = torch.Tensor(Y).to(self.device)
if PC is not None:
PC = torch.Tensor(PC).to(self.device)
if TC is not None:
TC = torch.Tensor(TC).to(self.device)
if n_samples == 0:
_, _, _, temp = self._model(X, Y, PC, TC, do_average=False, var_scale=0.0, eta_bn_prop=eta_bn_prop)
loss, NL, KLD = temp
losses = loss.to('cpu').detach().numpy()
else:
_, _, _, temp = self._model(X, Y, PC, TC, do_average=False, var_scale=1.0, eta_bn_prop=eta_bn_prop)
loss, NL, KLD = temp
losses = loss.to('cpu').detach().numpy()
for s in range(1, n_samples):
_, _, _, temp = self._model(X, Y, PC, TC, do_average=False, var_scale=1.0, eta_bn_prop=eta_bn_prop)
loss, NL, KLD = temp
losses += loss.to('cpu').detach().numpy()
losses /= float(n_samples)
return losses
def compute_theta(self, X, Y, PC, TC, eta_bn_prop=0.0):
"""
Return the latent document representation (mean of posterior of theta) for a given batch of X, Y, PC, and TC
"""
batch_size = self.get_batch_size(X)
if batch_size == 1:
X = np.expand_dims(X, axis=0)
if Y is not None and batch_size == 1:
Y = np.expand_dims(Y, axis=0)
if PC is not None and batch_size == 1:
PC = np.expand_dims(PC, axis=0)
if TC is not None and batch_size == 1:
TC = np.expand_dims(TC, axis=0)
X = torch.Tensor(X).to(self.device)
if Y is not None:
Y = torch.Tensor(Y).to(self.device)
if PC is not None:
PC = torch.Tensor(PC).to(self.device)
if TC is not None:
TC = torch.Tensor(TC).to(self.device)
theta, _, _, _ = self._model(X, Y, PC, TC, do_average=False, var_scale=0.0, eta_bn_prop=eta_bn_prop)
return theta.to('cpu').detach().numpy()
def get_weights(self):
"""
Return the topic-vocabulary deviation weights
"""
emb = self._model.beta_layer.to('cpu').weight.detach().numpy().T
self._model.beta_layer.to(self.device)
return emb
def get_bg(self):
"""
Return the background terms
"""
bg = self._model.beta_layer.to('cpu').bias.detach().numpy()
self._model.beta_layer.to(self.device)
return bg
def get_prior_weights(self):
"""
Return the weights associated with the prior covariates
"""
emb = self._model.prior_covar_weights.to('cpu').weight.detach().numpy().T
self._model.prior_covar_weights.to(self.device)
return emb
def get_covar_weights(self):
"""
Return the topic weight (deviations) associated with the topic covariates
"""
emb = self._model.beta_c_layer.to('cpu').weight.detach().numpy().T
self._model.beta_c_layer.to(self.device)
return emb
def get_covar_interaction_weights(self):
"""
Return the weights (deviations) associated with the topic-covariate interactions
"""
emb = self._model.beta_ci_layer.to('cpu').weight.detach().numpy().T
self._model.beta_ci_layer.to(self.device)
return emb
def get_batch_size(self, X):
"""
Get the batch size for a minibatch of data
:param X: the minibatch
:return: the size of the minibatch
"""
if len(X.shape) == 1:
batch_size = 1
else:
batch_size, _ = X.shape
return batch_size
def eval(self):
self._model.eval()
def train(self):
self._model.train()
class torchScholar(nn.Module):
def __init__(self, config, alpha, update_embeddings=True, init_emb=None, bg_init=None, device='cpu', classify_from_covars=False):
super(torchScholar, self).__init__()
# load the configuration
self.vocab_size = config['vocab_size']
self.words_emb_dim = config['embedding_dim']
self.n_topics = config['n_topics']
self.n_labels = config['n_labels']
self.n_prior_covars = config['n_prior_covars']
self.n_topic_covars = config['n_topic_covars']
self.classifier_layers = config['classifier_layers']
self.use_interactions = config['use_interactions']
self.l1_beta_reg = config['l1_beta_reg']
self.l1_beta_c_reg = config['l1_beta_c_reg']
self.l1_beta_ci_reg = config['l1_beta_ci_reg']
self.l2_prior_reg = config['l2_prior_reg']
self.device = device
self.classify_from_covars = classify_from_covars
# create a layer for prior covariates to influence the document prior
if self.n_prior_covars > 0:
self.prior_covar_weights = nn.Linear(self.n_prior_covars, self.n_topics, bias=False)
else:
self.prior_covar_weights = None
# create the encoder
self.embeddings_x_layer = nn.Linear(self.vocab_size, self.words_emb_dim, bias=False)
emb_size = self.words_emb_dim
classifier_input_dim = self.n_topics
if self.n_prior_covars > 0:
emb_size += self.n_prior_covars
if self.classify_from_covars:
classifier_input_dim += self.n_prior_covars
if self.n_topic_covars > 0:
emb_size += self.n_topic_covars
if self.classify_from_covars:
classifier_input_dim += self.n_topic_covars
if self.n_labels > 0:
emb_size += self.n_labels
self.encoder_dropout_layer = nn.Dropout(p=0.2)
if not update_embeddings:
self.embeddings_x_layer.weight.requires_grad = False
if init_emb is not None:
self.embeddings_x_layer.weight.data.copy_(torch.from_numpy(init_emb)).to(self.device)
else:
xavier_uniform_(self.embeddings_x_layer.weight)
# create the mean and variance components of the VAE
self.mean_layer = nn.Linear(emb_size, self.n_topics)
self.logvar_layer = nn.Linear(emb_size, self.n_topics)
self.mean_bn_layer = nn.BatchNorm1d(self.n_topics, eps=0.001, momentum=0.001, affine=True)
self.mean_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.n_topics))).to(self.device)
self.mean_bn_layer.weight.requires_grad = False
self.logvar_bn_layer = nn.BatchNorm1d(self.n_topics, eps=0.001, momentum=0.001, affine=True)
self.logvar_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.n_topics))).to(self.device)
self.logvar_bn_layer.weight.requires_grad = False
self.z_dropout_layer = nn.Dropout(p=0.2)
# create the decoder
self.beta_layer = nn.Linear(self.n_topics, self.vocab_size)
xavier_uniform_(self.beta_layer.weight)
if bg_init is not None:
self.beta_layer.bias.data.copy_(torch.from_numpy(bg_init))
self.beta_layer.bias.requires_grad = False
self.beta_layer = self.beta_layer.to(self.device)
if self.n_topic_covars > 0:
self.beta_c_layer = nn.Linear(self.n_topic_covars, self.vocab_size, bias=False).to(self.device)
if self.use_interactions:
self.beta_ci_layer = nn.Linear(self.n_topics * self.n_topic_covars, self.vocab_size, bias=False).to(self.device)
# create the classifier
if self.n_labels > 0:
if self.classifier_layers == 0:
self.classifier_layer_0 = nn.Linear(classifier_input_dim, self.n_labels).to(self.device)
else:
self.classifier_layer_0 = nn.Linear(classifier_input_dim, classifier_input_dim).to(self.device)
self.classifier_layer_1 = nn.Linear(classifier_input_dim, self.n_labels).to(self.device)
# create a final batchnorm layer
self.eta_bn_layer = nn.BatchNorm1d(self.vocab_size, eps=0.001, momentum=0.001, affine=True).to(self.device)
self.eta_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.vocab_size)).to(self.device))
self.eta_bn_layer.weight.requires_grad = False
# create the document prior terms
prior_mean = (np.log(alpha).T - np.mean(np.log(alpha), 1)).T
prior_var = (((1.0 / alpha) * (1 - (2.0 / self.n_topics))).T + (1.0 / (self.n_topics * self.n_topics)) * np.sum(1.0 / alpha, 1)).T
prior_mean = np.array(prior_mean).reshape((1, self.n_topics))
prior_logvar = np.array(np.log(prior_var)).reshape((1, self.n_topics))
self.prior_mean = torch.from_numpy(prior_mean).to(self.device)
self.prior_mean.requires_grad = False
self.prior_logvar = torch.from_numpy(prior_logvar).to(self.device)
self.prior_logvar.requires_grad = False
def forward(self, X, Y, PC, TC, compute_loss=True, do_average=True, eta_bn_prop=1.0, var_scale=1.0, l1_beta=None, l1_beta_c=None, l1_beta_ci=None):
"""
Do a forward pass of the model
:param X: np.array of word counts [batch_size x vocab_size]
:param Y: np.array of labels [batch_size x n_classes]
:param PC: np.array of covariates influencing the prior [batch_size x n_prior_covars]
:param TC: np.array of covariates with explicit topic deviations [batch_size x n_topic_covariates]
:param compute_loss: if True, compute and return the loss
:param do_average: if True, average the loss over the minibatch
:param eta_bn_prop: (float) a weight between 0 and 1 to interpolate between using and not using the final batchnorm layer
:param var_scale: (float) a parameter which can be used to scale the variance of the random noise in the VAE
:param l1_beta: np.array of prior variances for the topic weights
:param l1_beta_c: np.array of prior variances on topic covariate deviations
:param l1_beta_ci: np.array of prior variances on topic-covariate interactions
:return: document representation; reconstruction; label probs; (loss, if requested)
"""
# embed the word counts
en0_x = self.embeddings_x_layer(X)
encoder_parts = [en0_x]
# append additional components to the encoder, if given
if self.n_prior_covars > 0:
encoder_parts.append(PC)
if self.n_topic_covars > 0:
encoder_parts.append(TC)
if self.n_labels > 0:
encoder_parts.append(Y)
if len(encoder_parts) > 1:
en0 = torch.cat(encoder_parts, dim=1).to(self.device)
else:
en0 = en0_x
encoder_output = F.softplus(en0)
encoder_output_do = self.encoder_dropout_layer(encoder_output)
# compute the mean and variance of the document posteriors
posterior_mean = self.mean_layer(encoder_output_do)
posterior_logvar = self.logvar_layer(encoder_output_do)
posterior_mean_bn = self.mean_bn_layer(posterior_mean)
posterior_logvar_bn = self.logvar_bn_layer(posterior_logvar)
#posterior_mean_bn = posterior_mean
#posterior_logvar_bn = posterior_logvar
posterior_var = posterior_logvar_bn.exp().to(self.device)
# sample noise from a standard normal
eps = X.data.new().resize_as_(posterior_mean_bn.data).normal_().to(self.device)
# compute the sampled latent representation
z = posterior_mean_bn + posterior_var.sqrt() * eps * var_scale
z_do = self.z_dropout_layer(z)
# pass the document representations through a softmax
theta = F.softmax(z_do, dim=1)
# combine latent representation with topics and background
# beta layer here includes both the topic weights and the background term (as a bias)
eta = self.beta_layer(theta)
# add deviations for covariates (and interactions)
if self.n_topic_covars > 0:
eta = eta + self.beta_c_layer(TC)
if self.use_interactions:
theta_rsh = theta.unsqueeze(2)
tc_emb_rsh = TC.unsqueeze(1)
covar_interactions = theta_rsh * tc_emb_rsh
batch_size, _, _ = covar_interactions.shape
eta += self.beta_ci_layer(covar_interactions.reshape((batch_size, self.n_topics * self.n_topic_covars)))
# pass the unnormalized word probabilities through a batch norm layer
eta_bn = self.eta_bn_layer(eta)
#eta_bn = eta
# compute X recon with and without batchnorm on eta, and take a convex combination of them
X_recon_bn = F.softmax(eta_bn, dim=1)
X_recon_no_bn = F.softmax(eta, dim=1)
X_recon = eta_bn_prop * X_recon_bn + (1.0 - eta_bn_prop) * X_recon_no_bn
# predict labels
Y_recon = None
if self.n_labels > 0:
classifier_inputs = [theta]
if self.classify_from_covars:
if self.n_prior_covars > 0:
classifier_inputs.append(PC)
if self.n_topic_covars > 0:
classifier_inputs.append(TC)
if len(classifier_inputs) > 1:
classifier_input = torch.cat(classifier_inputs, dim=1).to(self.device)
else:
classifier_input = theta
if self.classifier_layers == 0:
decoded_y = self.classifier_layer_0(classifier_input)
elif self.classifier_layers == 1:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
decoded_y = self.classifier_layer_1(cls0_sp)
else:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
cls1 = self.classifier_layer_1(cls0_sp)
cls1_sp = F.softplus(cls1)
decoded_y = self.classifier_layer_2(cls1_sp)
Y_recon = F.softmax(decoded_y, dim=1)
# compute the document prior if using prior covariates
if self.n_prior_covars > 0:
prior_mean = self.prior_covar_weights(PC)
prior_logvar = self.prior_logvar.expand_as(posterior_logvar)
else:
prior_mean = self.prior_mean.expand_as(posterior_mean)
prior_logvar = self.prior_logvar.expand_as(posterior_logvar)
if compute_loss:
return theta, X_recon, Y_recon, self._loss(X, Y, X_recon, Y_recon, prior_mean, prior_logvar, posterior_mean_bn, posterior_logvar_bn, do_average, l1_beta, l1_beta_c, l1_beta_ci)
else:
return theta, X_recon, Y_recon
def _loss(self, X, Y, X_recon, Y_recon, prior_mean, prior_logvar, posterior_mean, posterior_logvar, do_average=True, l1_beta=None, l1_beta_c=None, l1_beta_ci=None):
# compute reconstruction loss
NL = -(X * (X_recon+1e-10).log()).sum(1)
# compute label loss
if self.n_labels > 0:
NL += -(Y * (Y_recon+1e-10).log()).sum(1)
# compute KLD
prior_var = prior_logvar.exp()
posterior_var = posterior_logvar.exp()
var_division = posterior_var / prior_var
diff = posterior_mean - prior_mean
diff_term = diff * diff / prior_var
logvar_division = prior_logvar - posterior_logvar
# put KLD together
KLD = 0.5 * ((var_division + diff_term + logvar_division).sum(1) - self.n_topics)
# combine
loss = (NL + KLD)
# add regularization on prior
if self.l2_prior_reg > 0 and self.n_prior_covars > 0:
loss += self.l2_prior_reg * torch.pow(self.prior_covar_weights.weight, 2).sum()
# add regularization on topic and topic covariate weights
if self.l1_beta_reg > 0 and l1_beta is not None:
l1_strengths_beta = torch.from_numpy(l1_beta).to(self.device)
beta_weights_sq = torch.pow(self.beta_layer.weight, 2)
loss += self.l1_beta_reg * (l1_strengths_beta * beta_weights_sq).sum()
if self.n_topic_covars > 0 and l1_beta_c is not None and self.l1_beta_c_reg > 0:
l1_strengths_beta_c = torch.from_numpy(l1_beta_c).to(self.device)
beta_c_weights_sq = torch.pow(self.beta_c_layer.weight, 2)
loss += self.l1_beta_c_reg * (l1_strengths_beta_c * beta_c_weights_sq).sum()
if self.n_topic_covars > 0 and self.use_interactions and l1_beta_c is not None and self.l1_beta_ci_reg > 0:
l1_strengths_beta_ci = torch.from_numpy(l1_beta_ci).to(self.device)
beta_ci_weights_sq = torch.pow(self.beta_ci_layer.weight, 2)
loss += self.l1_beta_ci_reg * (l1_strengths_beta_ci * beta_ci_weights_sq).sum()
# average losses if desired
if do_average:
return loss.mean(), NL.mean(), KLD.mean()
else:
return loss, NL, KLD
def predict_from_theta(self, theta, PC, TC):
# Predict labels from a distribution over topics
Y_recon = None
if self.n_labels > 0:
classifier_inputs = [theta]
if self.classify_from_covars:
if self.n_prior_covars > 0:
classifier_inputs.append(PC)
if self.n_topic_covars > 0:
classifier_inputs.append(TC)
if len(classifier_inputs) > 1:
classifier_input = torch.cat(classifier_inputs, dim=1).to(self.device)
else:
classifier_input = theta.to(self.device)
if self.classifier_layers == 0:
decoded_y = self.classifier_layer_0(classifier_input)
elif self.classifier_layers == 1:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
decoded_y = self.classifier_layer_1(cls0_sp)
else:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
cls1 = self.classifier_layer_1(cls0_sp)
cls1_sp = F.softplus(cls1)
decoded_y = self.classifier_layer_1(cls1_sp)
Y_recon = F.softmax(decoded_y, dim=1)
return Y_recon
# This is a simplified version of Contrastive Scholar
class torchContrastiveScholar(nn.Module):
def __init__(self, config, alpha, update_embeddings=True, init_emb=None, bg_init=None, device='cpu', classify_from_covars=False, topk=1):
super(torchContrastiveScholar, self).__init__()
# load the configuration
self.vocab_size = config['vocab_size']
self.words_emb_dim = config['embedding_dim']
self.n_topics = config['n_topics']
self.n_labels = config['n_labels']
self.n_prior_covars = config['n_prior_covars']
self.n_topic_covars = config['n_topic_covars']
self.classifier_layers = config['classifier_layers']
self.use_interactions = config['use_interactions']
self.l1_beta_reg = config['l1_beta_reg']
self.l1_beta_c_reg = config['l1_beta_c_reg']
self.l1_beta_ci_reg = config['l1_beta_ci_reg']
self.l2_prior_reg = config['l2_prior_reg']
self.device = device
self.classify_from_covars = classify_from_covars
# create a layer for prior covariates to influence the document prior
if self.n_prior_covars > 0:
self.prior_covar_weights = nn.Linear(self.n_prior_covars, self.n_topics, bias=False)
else:
self.prior_covar_weights = None
# create the encoder
self.embeddings_x_layer = nn.Linear(self.vocab_size, self.words_emb_dim, bias=False)
emb_size = self.words_emb_dim
classifier_input_dim = self.n_topics
if self.n_prior_covars > 0:
emb_size += self.n_prior_covars
if self.classify_from_covars:
classifier_input_dim += self.n_prior_covars
if self.n_topic_covars > 0:
emb_size += self.n_topic_covars
if self.classify_from_covars:
classifier_input_dim += self.n_topic_covars
if self.n_labels > 0:
emb_size += self.n_labels
self.encoder_dropout_layer = nn.Dropout(p=0.2)
if not update_embeddings:
self.embeddings_x_layer.weight.requires_grad = False
if init_emb is not None:
self.embeddings_x_layer.weight.data.copy_(torch.from_numpy(init_emb)).to(self.device)
else:
xavier_uniform_(self.embeddings_x_layer.weight)
# create the mean and variance components of the VAE
self.mean_layer = nn.Linear(emb_size, self.n_topics)
self.logvar_layer = nn.Linear(emb_size, self.n_topics)
self.mean_bn_layer = nn.BatchNorm1d(self.n_topics, eps=0.001, momentum=0.001, affine=True)
self.mean_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.n_topics))).to(self.device)
self.mean_bn_layer.weight.requires_grad = False
self.logvar_bn_layer = nn.BatchNorm1d(self.n_topics, eps=0.001, momentum=0.001, affine=True)
self.logvar_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.n_topics))).to(self.device)
self.logvar_bn_layer.weight.requires_grad = False
self.z_dropout_layer = nn.Dropout(p=0.2)
# create the decoder
self.beta_layer = nn.Linear(self.n_topics, self.vocab_size)
xavier_uniform_(self.beta_layer.weight)
if bg_init is not None:
self.beta_layer.bias.data.copy_(torch.from_numpy(bg_init))
self.beta_layer.bias.requires_grad = False
self.beta_layer = self.beta_layer.to(self.device)
if self.n_topic_covars > 0:
self.beta_c_layer = nn.Linear(self.n_topic_covars, self.vocab_size, bias=False).to(self.device)
if self.use_interactions:
self.beta_ci_layer = nn.Linear(self.n_topics * self.n_topic_covars, self.vocab_size, bias=False).to(self.device)
# create the classifier
if self.n_labels > 0:
if self.classifier_layers == 0:
self.classifier_layer_0 = nn.Linear(classifier_input_dim, self.n_labels).to(self.device)
else:
self.classifier_layer_0 = nn.Linear(classifier_input_dim, classifier_input_dim).to(self.device)
self.classifier_layer_1 = nn.Linear(classifier_input_dim, self.n_labels).to(self.device)
# create a final batchnorm layer
self.eta_bn_layer = nn.BatchNorm1d(self.vocab_size, eps=0.001, momentum=0.001, affine=True).to(self.device)
self.eta_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.vocab_size)).to(self.device))
self.eta_bn_layer.weight.requires_grad = False
# create the document prior terms
prior_mean = (np.log(alpha).T - np.mean(np.log(alpha), 1)).T
prior_var = (((1.0 / alpha) * (1 - (2.0 / self.n_topics))).T + (1.0 / (self.n_topics * self.n_topics)) * np.sum(1.0 / alpha, 1)).T
prior_mean = np.array(prior_mean).reshape((1, self.n_topics))
prior_logvar = np.array(np.log(prior_var)).reshape((1, self.n_topics))
self.prior_mean = torch.from_numpy(prior_mean).to(self.device)
self.prior_mean.requires_grad = False
self.prior_logvar = torch.from_numpy(prior_logvar).to(self.device)
self.prior_logvar.requires_grad = False
self.cos = torch.nn.CosineSimilarity()
self.topk = topk
def forward(self, X, Y, PC, TC, compute_loss=True, do_average=True, eta_bn_prop=1.0, var_scale=1.0, l1_beta=None, l1_beta_c=None, l1_beta_ci=None):
"""
Do a forward pass of the model
:param X: np.array of word counts [batch_size x vocab_size]
:param Y: np.array of labels [batch_size x n_classes]
:param PC: np.array of covariates influencing the prior [batch_size x n_prior_covars]
:param TC: np.array of covariates with explicit topic deviations [batch_size x n_topic_covariates]
:param compute_loss: if True, compute and return the loss
:param do_average: if True, average the loss over the minibatch
:param eta_bn_prop: (float) a weight between 0 and 1 to interpolate between using and not using the final batchnorm layer
:param var_scale: (float) a parameter which can be used to scale the variance of the random noise in the VAE
:param l1_beta: np.array of prior variances for the topic weights
:param l1_beta_c: np.array of prior variances on topic covariate deviations
:param l1_beta_ci: np.array of prior variances on topic-covariate interactions
:return: document representation; reconstruction; label probs; (loss, if requested)
"""
# embed the word counts
en0_x = self.embeddings_x_layer(X)
encoder_parts = [en0_x]
# append additional components to the encoder, if given
if self.n_prior_covars > 0:
encoder_parts.append(PC)
if self.n_topic_covars > 0:
encoder_parts.append(TC)
if self.n_labels > 0:
encoder_parts.append(Y)
if len(encoder_parts) > 1:
en0 = torch.cat(encoder_parts, dim=1).to(self.device)
else:
en0 = en0_x
encoder_output = F.softplus(en0)
encoder_output_do = self.encoder_dropout_layer(encoder_output)
# compute the mean and variance of the document posteriors
posterior_mean = self.mean_layer(encoder_output_do)
posterior_logvar = self.logvar_layer(encoder_output_do)
posterior_mean_bn = self.mean_bn_layer(posterior_mean)
posterior_logvar_bn = self.logvar_bn_layer(posterior_logvar)
#posterior_mean_bn = posterior_mean
#posterior_logvar_bn = posterior_logvar
posterior_var = posterior_logvar_bn.exp().to(self.device)
# sample noise from a standard normal
eps = X.data.new().resize_as_(posterior_mean_bn.data).normal_().to(self.device)
# compute the sampled latent representation
z = posterior_mean_bn + posterior_var.sqrt() * eps * var_scale
z_do = self.z_dropout_layer(z)
# pass the document representations through a softmax
theta = F.softmax(z_do, dim=1)
# combine latent representation with topics and background
# beta layer here includes both the topic weights and the background term (as a bias)
eta = self.beta_layer(theta)
# add deviations for covariates (and interactions)
if self.n_topic_covars > 0:
eta = eta + self.beta_c_layer(TC)
if self.use_interactions:
theta_rsh = theta.unsqueeze(2)
tc_emb_rsh = TC.unsqueeze(1)
covar_interactions = theta_rsh * tc_emb_rsh
batch_size, _, _ = covar_interactions.shape
eta += self.beta_ci_layer(covar_interactions.reshape((batch_size, self.n_topics * self.n_topic_covars)))
# pass the unnormalized word probabilities through a batch norm layer
eta_bn = self.eta_bn_layer(eta)
#eta_bn = eta
# compute X recon with and without batchnorm on eta, and take a convex combination of them
X_recon_bn = F.softmax(eta_bn, dim=1)
X_recon_no_bn = F.softmax(eta, dim=1)
X_recon = eta_bn_prop * X_recon_bn + (1.0 - eta_bn_prop) * X_recon_no_bn
##############################################################################################################################################################################################################################################
# contrastive component - instead of tdidf, we directly use the weights of reconstructed BoW, which provided similar results but faster computation
##############################################################################################################################################################################################################################################
max_ids = torch.topk(X_recon, k=self.topk, dim=1).indices
max_values = torch.topk(X_recon,k=self.topk,dim=1).values
total_words = torch.sum(X,1).unsqueeze(-1)
max_values = max_values*total_words
tmp_x = copy.copy(X)
contrastive_X = tmp_x.scatter_(1,max_ids, max_values)
contrastive_en0_x = self.embeddings_x_layer(contrastive_X)
contrastive_encoder_parts = [contrastive_en0_x]
# append additional components to the encoder, if given
if self.n_prior_covars > 0:
contrastive_encoder_parts.append(PC)
if self.n_topic_covars > 0:
contrastive_encoder_parts.append(TC)
if self.n_labels > 0:
contrastive_encoder_parts.append(Y)
if len(contrastive_encoder_parts) > 1:
contrastive_en0 = torch.cat(contrastive_encoder_parts, dim=1).to(self.device)
else:
contrastive_en0 = contrastive_en0_x
contrastive_encoder_output = F.softplus(contrastive_en0)
contrastive_encoder_output_do = self.encoder_dropout_layer(contrastive_encoder_output)
contrastive_posterior_mean = self.mean_layer(contrastive_encoder_output_do)
contrastive_posterior_logvar = self.logvar_layer(contrastive_encoder_output_do)
contrastive_posterior_mean_bn = self.mean_bn_layer(contrastive_posterior_mean)
contrastive_posterior_logvar_bn = self.logvar_bn_layer(contrastive_posterior_logvar)
contrastive_posterior_var = contrastive_posterior_logvar_bn.exp().to(self.device)
contrastive_z = contrastive_posterior_mean_bn + contrastive_posterior_var.sqrt() * eps * var_scale
normalized_z = F.normalize(z)
normalized_contrastive_z = F.normalize(contrastive_z)
contrastive_loss = self.cos(normalized_z, normalized_contrastive_z).mean()
# contrastive_loss = self.cos(z,contrastive_z).mean()
# predict labels
Y_recon = None
if self.n_labels > 0:
classifier_inputs = [theta]
if self.classify_from_covars:
if self.n_prior_covars > 0:
classifier_inputs.append(PC)
if self.n_topic_covars > 0:
classifier_inputs.append(TC)
if len(classifier_inputs) > 1:
classifier_input = torch.cat(classifier_inputs, dim=1).to(self.device)
else:
classifier_input = theta
if self.classifier_layers == 0:
decoded_y = self.classifier_layer_0(classifier_input)
elif self.classifier_layers == 1:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
decoded_y = self.classifier_layer_1(cls0_sp)
else:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
cls1 = self.classifier_layer_1(cls0_sp)
cls1_sp = F.softplus(cls1)
decoded_y = self.classifier_layer_2(cls1_sp)
Y_recon = F.softmax(decoded_y, dim=1)
# compute the document prior if using prior covariates
if self.n_prior_covars > 0:
prior_mean = self.prior_covar_weights(PC)
prior_logvar = self.prior_logvar.expand_as(posterior_logvar)
else:
prior_mean = self.prior_mean.expand_as(posterior_mean)
prior_logvar = self.prior_logvar.expand_as(posterior_logvar)
if compute_loss:
return theta, X_recon, Y_recon, self._loss(X, Y, X_recon, Y_recon, prior_mean, prior_logvar, posterior_mean_bn, posterior_logvar_bn, do_average, l1_beta, l1_beta_c, l1_beta_ci, contrastive_loss)
else:
return theta, X_recon, Y_recon
def _loss(self, X, Y, X_recon, Y_recon, prior_mean, prior_logvar, posterior_mean, posterior_logvar, do_average=True, l1_beta=None, l1_beta_c=None, l1_beta_ci=None, contrastive_loss=None):
# compute reconstruction loss
NL = -(X * (X_recon+1e-10).log()).sum(1)
# compute label loss
if self.n_labels > 0:
NL += -(Y * (Y_recon+1e-10).log()).sum(1)
# compute KLD
prior_var = prior_logvar.exp()
posterior_var = posterior_logvar.exp()
var_division = posterior_var / prior_var
diff = posterior_mean - prior_mean
diff_term = diff * diff / prior_var
logvar_division = prior_logvar - posterior_logvar
# put KLD together
KLD = 0.5 * ((var_division + diff_term + logvar_division).sum(1) - self.n_topics)
# combine
loss = (NL + KLD)
if contrastive_loss: loss += contrastive_loss
# add regularization on prior
if self.l2_prior_reg > 0 and self.n_prior_covars > 0:
loss += self.l2_prior_reg * torch.pow(self.prior_covar_weights.weight, 2).sum()
# add regularization on topic and topic covariate weights
if self.l1_beta_reg > 0 and l1_beta is not None:
l1_strengths_beta = torch.from_numpy(l1_beta).to(self.device)
beta_weights_sq = torch.pow(self.beta_layer.weight, 2)
loss += self.l1_beta_reg * (l1_strengths_beta * beta_weights_sq).sum()
if self.n_topic_covars > 0 and l1_beta_c is not None and self.l1_beta_c_reg > 0:
l1_strengths_beta_c = torch.from_numpy(l1_beta_c).to(self.device)
beta_c_weights_sq = torch.pow(self.beta_c_layer.weight, 2)
loss += self.l1_beta_c_reg * (l1_strengths_beta_c * beta_c_weights_sq).sum()
if self.n_topic_covars > 0 and self.use_interactions and l1_beta_c is not None and self.l1_beta_ci_reg > 0:
l1_strengths_beta_ci = torch.from_numpy(l1_beta_ci).to(self.device)
beta_ci_weights_sq = torch.pow(self.beta_ci_layer.weight, 2)
loss += self.l1_beta_ci_reg * (l1_strengths_beta_ci * beta_ci_weights_sq).sum()
# average losses if desired
if do_average:
return loss.mean(), NL.mean(), KLD.mean()
else:
return loss, NL, KLD
def predict_from_theta(self, theta, PC, TC):
# Predict labels from a distribution over topics
Y_recon = None
if self.n_labels > 0:
classifier_inputs = [theta]
if self.classify_from_covars:
if self.n_prior_covars > 0:
classifier_inputs.append(PC)
if self.n_topic_covars > 0:
classifier_inputs.append(TC)
if len(classifier_inputs) > 1:
classifier_input = torch.cat(classifier_inputs, dim=1).to(self.device)
else:
classifier_input = theta.to(self.device)
if self.classifier_layers == 0:
decoded_y = self.classifier_layer_0(classifier_input)
elif self.classifier_layers == 1:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
decoded_y = self.classifier_layer_1(cls0_sp)
else:
cls0 = self.classifier_layer_0(classifier_input)
cls0_sp = F.softplus(cls0)
cls1 = self.classifier_layer_1(cls0_sp)
cls1_sp = F.softplus(cls1)
decoded_y = self.classifier_layer_1(cls1_sp)
Y_recon = F.softmax(decoded_y, dim=1)
return Y_recon
class torchTrueContrastiveScholar(nn.Module):
def __init__(self, config, alpha, update_embeddings=True, init_emb=None, bg_init=None, device='cpu', classify_from_covars=False, topk=1):
super(torchTrueContrastiveScholar, self).__init__()
# load the configuration
self.vocab_size = config['vocab_size']
self.words_emb_dim = config['embedding_dim']
self.n_topics = config['n_topics']
self.n_labels = config['n_labels']
self.n_prior_covars = config['n_prior_covars']
self.n_topic_covars = config['n_topic_covars']
self.classifier_layers = config['classifier_layers']
self.use_interactions = config['use_interactions']
self.l1_beta_reg = config['l1_beta_reg']
self.l1_beta_c_reg = config['l1_beta_c_reg']
self.l1_beta_ci_reg = config['l1_beta_ci_reg']
self.l2_prior_reg = config['l2_prior_reg']
self.device = device
self.classify_from_covars = classify_from_covars
# create a layer for prior covariates to influence the document prior
if self.n_prior_covars > 0:
self.prior_covar_weights = nn.Linear(self.n_prior_covars, self.n_topics, bias=False)
else:
self.prior_covar_weights = None
# create the encoder
self.embeddings_x_layer = nn.Linear(self.vocab_size, self.words_emb_dim, bias=False)
emb_size = self.words_emb_dim
classifier_input_dim = self.n_topics
if self.n_prior_covars > 0:
emb_size += self.n_prior_covars
if self.classify_from_covars:
classifier_input_dim += self.n_prior_covars
if self.n_topic_covars > 0:
emb_size += self.n_topic_covars
if self.classify_from_covars:
classifier_input_dim += self.n_topic_covars
if self.n_labels > 0:
emb_size += self.n_labels
self.encoder_dropout_layer = nn.Dropout(p=0.2)
if not update_embeddings:
self.embeddings_x_layer.weight.requires_grad = False
if init_emb is not None:
self.embeddings_x_layer.weight.data.copy_(torch.from_numpy(init_emb)).to(self.device)
else:
xavier_uniform_(self.embeddings_x_layer.weight)
# create the mean and variance components of the VAE
self.mean_layer = nn.Linear(emb_size, self.n_topics)
self.logvar_layer = nn.Linear(emb_size, self.n_topics)
self.mean_bn_layer = nn.BatchNorm1d(self.n_topics, eps=0.001, momentum=0.001, affine=True)
self.mean_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.n_topics))).to(self.device)
self.mean_bn_layer.weight.requires_grad = False
self.logvar_bn_layer = nn.BatchNorm1d(self.n_topics, eps=0.001, momentum=0.001, affine=True)
self.logvar_bn_layer.weight.data.copy_(torch.from_numpy(np.ones(self.n_topics))).to(self.device)
self.logvar_bn_layer.weight.requires_grad = False
self.z_dropout_layer = nn.Dropout(p=0.2)
# create the decoder
self.beta_layer = nn.Linear(self.n_topics, self.vocab_size)
xavier_uniform_(self.beta_layer.weight)
if bg_init is not None:
self.beta_layer.bias.data.copy_(torch.from_numpy(bg_init))
self.beta_layer.bias.requires_grad = False
self.beta_layer = self.beta_layer.to(self.device)
if self.n_topic_covars > 0:
self.beta_c_layer = nn.Linear(self.n_topic_covars, self.vocab_size, bias=False).to(self.device)
if self.use_interactions:
self.beta_ci_layer = nn.Linear(self.n_topics * self.n_topic_covars, self.vocab_size, bias=False).to(self.device)
# create the classifier
if self.n_labels > 0:
if self.classifier_layers == 0:
self.classifier_layer_0 = nn.Linear(classifier_input_dim, self.n_labels).to(self.device)
else:
self.classifier_layer_0 = nn.Linear(classifier_input_dim, classifier_input_dim).to(self.device)
self.classifier_layer_1 = nn.Linear(classifier_input_dim, self.n_labels).to(self.device)