-
Notifications
You must be signed in to change notification settings - Fork 1
/
choice_models.py
693 lines (521 loc) · 25 KB
/
choice_models.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
import time
from abc import ABC, abstractmethod
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as nnf
from scipy.stats import stats
from tqdm import tqdm
from datasets import SFShop, YoochooseCats, SFWork
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
device = torch.device('cpu')
# From https://github.com/pytorch/pytorch/issues/31829
@torch.jit.script
def logsumexp(x: torch.Tensor, dim: int) -> torch.Tensor:
m, _ = x.max(dim=dim)
mask = m == -float('inf')
s = (x - m.masked_fill_(mask, 0).unsqueeze(dim=dim)).exp().sum(dim=dim)
return s.masked_fill_(mask, 1).log() + m.masked_fill_(mask, -float('inf'))
class ChoiceModel(nn.Module):
def loss(self, y_hat, y, weights):
"""
The error in inferred log-probabilities given observations
:param y_hat: log(choice probabilities)
:param y: observed choices
:return: the loss
"""
return torch.dot(nnf.nll_loss(y_hat, y, reduction='none').squeeze(), weights) / len(y)
def accuracy(self, y_hat, y):
"""
Compute accuracy (fraction of choice set correctly predicted)
:param y_hat: log(choice probabilities)
:param y: observed choices
:return: the accuracy
"""
return (y_hat.argmax(1).int() == y.int()).float().mean()
def mean_relative_rank(self, y_hat, y):
"""
Compute mean rank of correct answer in output sorted by probability
:param y_hat:
:param y:
:return:
"""
return np.mean(self.relative_ranks(y_hat, y))
def relative_ranks(self, y_hat, y):
"""
Compute mean rank of correct answer in output sorted by probability
:param y_hat:
:param y:
:return:
"""
y_hat = y_hat.squeeze().cpu()
y = y.squeeze().cpu()
choice_set_lengths = np.array((~torch.isinf(y_hat)).sum(1))
ranks = stats.rankdata(-y_hat.detach().numpy(), method='average', axis=1)[np.arange(len(y)), y] - 1
return ranks / (choice_set_lengths - 1)
@property
def num_params(self):
return sum(param.numel() for param in self.parameters() if param.requires_grad)
class ItemIdentityChoiceModel(ChoiceModel, ABC):
@abstractmethod
def forward(self, choice_sets):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:return: log(choice probabilities) over every choice set
"""
pass
class ChooserFeatureChoiceModel(ChoiceModel, ABC):
@abstractmethod
def forward(self, choice_sets, chooser_features):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:param chooser_features: features of the chooser in each sample
:return: log(choice probabilities) over every choice set
"""
pass
class ItemFeatureChoiceModel(ChoiceModel, ABC):
@abstractmethod
def forward(self, choice_set_features, choice_set_lengths):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_set_features: the choice sets, with item features
:param choice_set_lengths: number of items in each choice set
:return: log(choice probabilities) over every choice set
"""
class ItemChooserFeatureChoiceModel(ChoiceModel, ABC):
@abstractmethod
def forward(self, choice_set_features, choice_set_lengths, chooser_features):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_set_features: the choice sets, with item features
:param choice_set_lengths: number of items in each choice set
:param chooser_features: features of the chooser in each sample
:return: log(choice probabilities) over every choice set
"""
pass
class LowRankCDM(ItemIdentityChoiceModel):
"""
Implementation of low-rank CDM.
Adapted from https://github.com/arjunsesh/cdm-icml.
"""
name = 'low-rank-cdm'
def __init__(self, num_items, rank=2):
"""
Initialize a low rank CDM model for inference
:param num_items: size of U
:param rank: the rank of the CDM
"""
super().__init__()
self.num_items = num_items
self.embedding_dim = rank
self.target_embedding = nn.Parameter(torch.randn((self.num_items, self.embedding_dim)))
self.context_embedding = nn.Parameter(torch.randn((self.num_items, self.embedding_dim)))
def forward(self, choice_sets):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:return: log(choice probabilities) over every choice set
"""
context_vecs = self.context_embedding * choice_sets
target_vecs = self.target_embedding * choice_sets
context_sums = context_vecs.sum(-2, keepdim=True) - context_vecs
utilities = (target_vecs * context_sums).sum(-1, keepdim=True)
utilities[choice_sets == 0] = -np.inf
return nnf.log_softmax(utilities, 1)
class Logit(ItemIdentityChoiceModel):
name = 'logit'
table_name = 'Logit'
def __init__(self, num_items):
"""
Initialize an MNL model for inference
:param num_items: size of U
"""
super().__init__()
self.num_items = num_items
self.utilities = nn.Parameter(torch.zeros(self.num_items, 1))
def forward(self, choice_sets):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:return: log(choice probabilities) over every choice set
"""
utilities = self.utilities * choice_sets
utilities[choice_sets == 0] = -np.inf
return nnf.log_softmax(utilities, 1)
class CDM(ItemIdentityChoiceModel):
name = 'cdm'
table_name = 'CDM'
def __init__(self, num_items):
super().__init__()
self.num_items = num_items
self.pulls = nn.Parameter(torch.zeros(self.num_items, self.num_items))
def forward(self, choice_sets):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:return: log(choice probabilities) over every choice set
"""
utilities = ((choice_sets.squeeze() @ self.pulls).unsqueeze(-1) - torch.diag(self.pulls)[:, None]) * choice_sets
utilities[choice_sets == 0] = -np.inf
return nnf.log_softmax(utilities, 1)
class SingleContextCDM(ItemIdentityChoiceModel):
name = 'single-context-cdm'
def __init__(self, num_items, context_item):
super().__init__()
self.num_items = num_items
self.context_item = context_item
self.utilities = nn.Parameter(torch.zeros(self.num_items))
self.pulls = nn.Parameter(torch.zeros(self.num_items))
def forward(self, choice_sets):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:return: log(choice probabilities) over every choice set
"""
utilities = (self.utilities + (self.pulls * choice_sets[:, self.context_item])).unsqueeze(-1)
utilities[choice_sets == 0] = -np.inf
return nnf.log_softmax(utilities, 1)
class MultinomialLogit(ChooserFeatureChoiceModel):
name = 'multinomial-logit'
table_name = 'MNL'
def __init__(self, num_items, num_chooser_features):
"""
Initialize an MNL model for inference
:param num_items: size of U
:param num_chooser_features: number of chooser features
"""
super().__init__()
self.num_chooser_features = num_chooser_features
self.num_items = num_items
self.coeffs = nn.Parameter(torch.ones(self.num_items, num_chooser_features))
self.intercepts = nn.Parameter(torch.zeros(self.num_items, 1))
def forward(self, choice_sets, chooser_features):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:param chooser_features: features of the chooser in each sample
:return: log(choice probabilities) over every choice set
"""
utilities = (self.coeffs * chooser_features[:, None, :]).sum(axis=2, keepdim=True) + self.intercepts
utilities = utilities * choice_sets
utilities[choice_sets == 0] = -np.inf
return nnf.log_softmax(utilities, 1)
class MultinomialCDM(ChooserFeatureChoiceModel):
name = 'multinomial-cdm'
table_name = 'MCDM'
def __init__(self, num_items, num_chooser_features):
super().__init__()
self.num_chooser_features = num_chooser_features
self.num_items = num_items
self.coeffs = nn.Parameter(torch.ones(self.num_items, num_chooser_features))
self.pulls = nn.Parameter(torch.zeros(self.num_items, self.num_items))
def forward(self, choice_sets, chooser_features):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:param chooser_features: features of the chooser in each sample
:return: log(choice probabilities) over every choice set
"""
utilities = (self.coeffs * chooser_features[:, None, :]).sum(axis=2, keepdim=True)
utilities = utilities + (choice_sets.squeeze() @ self.pulls).unsqueeze(-1) - torch.diag(self.pulls)[:, None]
utilities = utilities * choice_sets
utilities[choice_sets == 0] = -np.inf
return nnf.log_softmax(utilities, 1)
class MultinomialLowRankCDM(ChooserFeatureChoiceModel):
name = 'multinomial-low-rank-cdm'
table_name = 'rank-2 MCDM'
def __init__(self, num_items, num_chooser_features, rank=2):
super().__init__()
self.num_chooser_features = num_chooser_features
self.num_items = num_items
self.coeffs = nn.Parameter(torch.ones(self.num_items, num_chooser_features))
self.embedding_dim = rank
self.target_embedding = nn.Parameter(torch.randn((self.num_items, self.embedding_dim)))
self.context_embedding = nn.Parameter(torch.randn((self.num_items, self.embedding_dim)))
def forward(self, choice_sets, chooser_features):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:param chooser_features: features of the chooser in each sample
:return: log(choice probabilities) over every choice set
"""
context_vecs = self.context_embedding * choice_sets
target_vecs = self.target_embedding * choice_sets
context_sums = context_vecs.sum(-2, keepdim=True) - context_vecs
utilities = (self.coeffs * chooser_features[:, None, :]).sum(axis=2, keepdim=True)
utilities = utilities * choice_sets
utilities = utilities + (target_vecs * context_sums).sum(-1, keepdim=True)
utilities[choice_sets == 0] = -np.inf
return nnf.log_softmax(utilities, 1)
class ConditionalLogit(ItemFeatureChoiceModel):
name = 'conditional-logit'
table_name = 'CL'
def __init__(self, num_item_feats):
"""
:param num_item_feats: number of item features
"""
super().__init__()
self.num_item_feats = num_item_feats
self.theta = nn.Parameter(torch.zeros(self.num_item_feats))
def forward(self, choice_set_features, choice_set_lengths):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_set_features: the choice sets, with item features
:param choice_set_lengths: number of items in each cchoice set
:return: log(choice probabilities) over every choice set
"""
batch_size, max_choice_set_len, num_feats = choice_set_features.size()
utilities = (self.theta * choice_set_features).sum(-1)
utilities[torch.arange(max_choice_set_len)[None, :].to(device) >= choice_set_lengths[:, None]] = -np.inf
return nnf.log_softmax(utilities, 1)
class ConditionalMultinomialLogit(ItemChooserFeatureChoiceModel):
name = 'conditional-multinomial-logit'
table_name = 'CML'
def __init__(self, num_item_feats, num_chooser_feats):
"""
:param num_item_feats: number of item features
"""
super().__init__()
self.num_item_feats = num_item_feats
self.num_chooser_feats = num_chooser_feats
self.theta = nn.Parameter(torch.zeros(self.num_item_feats, 1))
self.B = nn.Parameter(torch.zeros(self.num_item_feats, self.num_chooser_feats))
def forward(self, choice_set_features, choice_set_lengths, chooser_features):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_set_features: the choice sets, with item features
:param choice_set_lengths: number of items in each choice set
:param chooser_features: features of the chooser in each sample
:return: log(choice probabilities) over every choice set
"""
batch_size, max_choice_set_len, num_feats = choice_set_features.size()
utilities = ((self.theta + self.B @ chooser_features.unsqueeze(-1))[:, None, :, 0] * choice_set_features).sum(-1)
utilities[torch.arange(max_choice_set_len)[None, :].to(device) >= choice_set_lengths[:, None]] = -np.inf
return nnf.log_softmax(utilities, 1)
class MLPConditionalMultinomialLogit(ItemChooserFeatureChoiceModel):
name = 'mlp-conditional-multinomial-logit'
table_name = 'MLP-CML'
def __init__(self, num_item_feats, num_chooser_feats):
"""
:param num_item_feats: number of item features
"""
super().__init__()
self.num_item_feats = num_item_feats
self.num_chooser_feats = num_chooser_feats
self.theta = nn.Parameter(torch.zeros(self.num_item_feats, 1))
self.mlp = nn.Sequential(
nn.Linear(self.num_chooser_feats, self.num_chooser_feats),
nn.ReLU(),
nn.Linear(self.num_chooser_feats, self.num_item_feats),
nn.ReLU(),
nn.Linear(self.num_item_feats, self.num_item_feats)
)
def forward(self, choice_set_features, choice_set_lengths, chooser_features):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_set_features: the choice sets, with item features
:param choice_set_lengths: number of items in each choice set
:param chooser_features: features of the chooser in each sample
:return: log(choice probabilities) over every choice set
"""
batch_size, max_choice_set_len, num_feats = choice_set_features.size()
utilities = ((self.theta + self.mlp(chooser_features).unsqueeze(-1))[:, None, :, 0] * choice_set_features).sum(-1)
utilities[torch.arange(max_choice_set_len)[None, :] >= choice_set_lengths[:, None]] = -np.inf
return nnf.log_softmax(utilities, 1)
class LCL(ItemFeatureChoiceModel):
name = 'lcl'
table_name = 'LCL'
def __init__(self, num_item_feats):
"""
:param num_item_feats: number of item features
"""
super().__init__()
self.num_item_feats = num_item_feats
self.theta = nn.Parameter(torch.zeros(self.num_item_feats))
self.A = nn.Parameter(torch.zeros(self.num_item_feats, self.num_item_feats))
def forward(self, choice_set_features, choice_set_lengths):
batch_size, max_choice_set_len, num_feats = choice_set_features.size()
# Compute mean of each feature over each choice set
mean_choice_set_features = choice_set_features.sum(1) / choice_set_lengths.unsqueeze(-1)
# Compute context effect in each sample
context_effects = self.A @ mean_choice_set_features.unsqueeze(-1)
# Compute context-adjusted utility of every item
utilities = ((self.theta.unsqueeze(-1) + context_effects).view(batch_size, 1, -1) * choice_set_features).sum(-1)
utilities[torch.arange(max_choice_set_len).to(device).unsqueeze(0) >= choice_set_lengths.unsqueeze(-1)] = -np.inf
return nn.functional.log_softmax(utilities, 1)
class MultinomialLCL(ItemChooserFeatureChoiceModel):
name = 'multinomial-lcl'
table_name = 'MLCL'
def __init__(self, num_item_feats, num_chooser_feats):
"""
:param num_item_feats: number of item features
"""
super().__init__()
self.num_item_feats = num_item_feats
self.num_chooser_feats = num_chooser_feats
self.theta = nn.Parameter(torch.zeros(self.num_item_feats))
self.A = nn.Parameter(torch.zeros(self.num_item_feats, self.num_item_feats))
self.B = nn.Parameter(torch.zeros(self.num_item_feats, self.num_chooser_feats))
def forward(self, choice_set_features, choice_set_lengths, chooser_features):
batch_size, max_choice_set_len, num_feats = choice_set_features.size()
# Compute mean of each feature over each choice set
mean_choice_set_features = choice_set_features.sum(1) / choice_set_lengths.unsqueeze(-1)
# Compute context effect in each sample
context_effects = self.A @ mean_choice_set_features.unsqueeze(-1)
# Compute per-chooser effect on utilities
chooser_prefs = self.B @ chooser_features.unsqueeze(-1)
# Compute context-adjusted utility of every item
utilities = ((self.theta.unsqueeze(-1) + context_effects + chooser_prefs).view(batch_size, 1, -1) * choice_set_features).sum(-1)
utilities[torch.arange(max_choice_set_len).to(device).unsqueeze(0) >= choice_set_lengths.unsqueeze(-1)] = -np.inf
return nn.functional.log_softmax(utilities, 1)
class MLPMultinomialLCL(ItemChooserFeatureChoiceModel):
name = 'mlp-multinomial-lcl'
table_name = 'MLP-MLCL'
def __init__(self, num_item_feats, num_chooser_feats):
"""
:param num_item_feats: number of item features
"""
super().__init__()
self.num_item_feats = num_item_feats
self.num_chooser_feats = num_chooser_feats
self.theta = nn.Parameter(torch.zeros(self.num_item_feats))
self.A = nn.Parameter(torch.zeros(self.num_item_feats, self.num_item_feats))
self.mlp = nn.Sequential(
nn.Linear(self.num_chooser_feats, self.num_chooser_feats),
nn.ReLU(),
nn.Linear(self.num_chooser_feats, self.num_item_feats),
nn.ReLU(),
nn.Linear(self.num_item_feats, self.num_item_feats)
)
def forward(self, choice_set_features, choice_set_lengths, chooser_features):
batch_size, max_choice_set_len, num_feats = choice_set_features.size()
# Compute mean of each feature over each choice set
mean_choice_set_features = choice_set_features.sum(1) / choice_set_lengths.unsqueeze(-1)
# Compute context effect in each sample
context_effects = self.A @ mean_choice_set_features.unsqueeze(-1)
# Compute per-chooser effect on utilities
chooser_prefs = self.mlp(chooser_features).unsqueeze(-1)
# Compute context-adjusted utility of every item
utilities = ((self.theta.unsqueeze(-1) + context_effects + chooser_prefs).view(batch_size, 1, -1) * choice_set_features).sum(-1)
utilities[torch.arange(max_choice_set_len).to(device).unsqueeze(0) >= choice_set_lengths.unsqueeze(-1)] = -np.inf
return nn.functional.log_softmax(utilities, 1)
class MixedLogit(ItemIdentityChoiceModel):
name = 'mixed-logit'
def __init__(self, num_items, num_components):
super().__init__()
self.num_items = num_items
self.num_components = num_components
self.utilities = nn.Parameter(torch.rand(self.num_items, self.num_components), requires_grad=True)
self.mixture_weights = nn.Parameter(torch.ones(self.num_components), requires_grad=True)
def forward(self, choice_sets):
"""
Compute log(choice probabilities) of items in choice sets
:param choice_sets: the choice sets
:return: log(choice probabilities) over every choice set
"""
utilities = self.utilities * choice_sets
utilities[choice_sets.squeeze() == 0] = -np.inf
log_probs = nnf.log_softmax(utilities, 1)
# Combine the MNLs into single probability using weights
# using the torch.logsumexp fix (https://github.com/pytorch/pytorch/issues/31829)
return logsumexp(log_probs + torch.log_softmax(self.mixture_weights, 0), 2).unsqueeze(-1)
class EMAlgorithmQ(nn.Module):
def __init__(self, responsibilities, utilities_init):
super().__init__()
self.responsibilities = responsibilities
self.utilities = nn.Parameter(utilities_init, requires_grad=True)
def forward(self, choice_sets, choices):
samples = choices.size(0)
# Compute utility of each item under each logit
utilities = self.utilities * choice_sets
utilities[choice_sets.squeeze() == 0] = -np.inf
log_probs = nnf.log_softmax(utilities, 1)[torch.arange(samples), choices.squeeze()]
return - (self.responsibilities * log_probs).sum()
def fit(model, data, epochs=500, learning_rate=5e-2, l2_lambda=1e-4, show_live_loss=False, show_progress=True):
"""
Fit a choice model to data using the given optimizer.
:param model: a nn.Module
:param data:
:param epochs: number of optimization epochs
:param learning_rate: step size hyperparameter for Rprop
:param l2_lambda: regularization hyperparameter
:param show_live_loss: if True, add loss/accuracy to progressbar. Adds ~50% overhead
"""
torch.set_num_threads(1)
optimizer = torch.optim.Rprop(model.parameters(), lr=learning_rate)
# torch.autograd.set_detect_anomaly(True)
choices, weights = data[-2:]
progress_bar = tqdm(range(epochs), total=epochs) if show_progress else range(epochs)
for epoch in progress_bar:
model.train()
accuracies = []
losses = []
optimizer.zero_grad()
loss = model.loss(model(*data[:-2]), choices, weights)
l2_reg = torch.tensor(0.).to(device)
for param in model.parameters():
l2_reg += torch.pow(param, 2).sum()
loss += l2_lambda * l2_reg
loss.backward(retain_graph=None if epoch != epochs - 1 else True)
with torch.no_grad():
gradient = torch.stack([(item.grad ** 2).sum() for item in model.parameters()]).sum()
if gradient.item() < 10 ** -8:
break
optimizer.step()
if show_progress and show_live_loss:
model.eval()
with torch.no_grad():
accuracy = model.accuracy(model(*data[:-2]), choices)
losses.append(loss.detach())
accuracies.append(accuracy)
if show_progress and show_live_loss:
progress_bar.set_description(f'Loss: {np.mean(losses):.4f}, Accuracy: {np.mean(accuracies):.4f}, Grad: {gradient.item():.3e}. Epochs')
loss = model.loss(model(*data[:-2]), choices, weights)
loss.backward()
with torch.no_grad():
gradient = torch.stack([(item.grad ** 2).sum() for item in model.parameters()]).sum()
if show_progress:
print('Done. Final gradient:', gradient.item(), 'Final NLL:', loss.item() * len(data[-1]))
return loss.item() * len(data[-1])
def mixed_logit_em(model, choice_sets, choices, timeout_min=60):
samples = choices.size(0)
start_time = time.time()
# Loop until timeout or gradient norm < 10^-6
while True:
utilities = model.utilities * choice_sets
utilities[choice_sets.squeeze() == 0] = -np.inf
log_probs = nnf.log_softmax(utilities, 1)[torch.arange(samples), choices.squeeze()]
responsibilities = nnf.softmax(log_probs + torch.log_softmax(model.mixture_weights, 0), 1)
Q = EMAlgorithmQ(responsibilities, model.utilities.data)
optimizer = torch.optim.Rprop(Q.parameters(), lr=0.01)
for epoch in range(100):
loss = Q(choice_sets, choices)
optimizer.zero_grad()
loss.backward(retain_graph=True)
with torch.no_grad():
gradient = torch.stack([(item.grad ** 2).sum() for item in Q.parameters()]).sum()
if gradient.item() < 10 ** -7:
break
if timeout_min is not None:
if time.time() - start_time > timeout_min * 60:
break
optimizer.step()
if timeout_min is not None:
if time.time() - start_time > timeout_min * 60:
break
model.mixture_weights.data = torch.log(responsibilities.mean(0))
model.utilities.data = Q.utilities.data
loss = nnf.nll_loss(model(choice_sets), choices, reduction='sum')
model.zero_grad()
loss.backward()
with torch.no_grad():
gradient = torch.stack([(item.grad ** 2).sum() for item in model.parameters()]).sum()
if gradient.item() < 10 ** -6:
break
return model, nnf.nll_loss(model(choice_sets), choices, reduction='sum').item()
if __name__ == '__main__':
choice_sets, choices, person_df = SFWork.load_pytorch()
model = Logit(len(choice_sets[0]))
fit(model, (choice_sets, choices, torch.ones(len(choices))), l2_lambda=10**-4, show_live_loss=True)