Sequential Recommendation for cold-start users with meta transitional learning
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 5.9KB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. from collections import OrderedDict
  2. import torch
  3. import torch.nn as nn
  4. from torch.nn import functional as F
  5. class Embedding(nn.Module):
  6. def __init__(self, num_ent, parameter):
  7. super(Embedding, self).__init__()
  8. # self.device = torch.device('cuda:0')
  9. self.device = torch.device(parameter['device'])
  10. self.es = parameter['embed_dim']
  11. self.embedding = nn.Embedding(num_ent + 1, self.es)
  12. nn.init.xavier_uniform_(self.embedding.weight)
  13. def forward(self, triples):
  14. idx = [[[t[0], t[2]] for t in batch] for batch in triples]
  15. idx = torch.LongTensor(idx).to(self.device)
  16. return self.embedding(idx)
  17. class MetaLearner(nn.Module):
  18. def __init__(self, K, embed_size=100, num_hidden1=500, num_hidden2=200, out_size=100, dropout_p=0.5):
  19. super(MetaLearner, self).__init__()
  20. self.embed_size = embed_size
  21. self.K = K
  22. # self.out_size = out_size
  23. # self.hidden_size = out_size
  24. self.out_size = embed_size
  25. self.hidden_size = embed_size
  26. self.rnn = nn.LSTM(embed_size,self.hidden_size,2,dropout=0.2)
  27. # nn.init.xavier_normal_(self.rnn.all_weights)
  28. def forward(self, inputs):
  29. size = inputs.shape
  30. x = torch.stack([inputs[:,0,0,:],inputs[:,0,1,:],inputs[:,1,1,:]],dim=1)
  31. x = x.transpose(0,1)
  32. _,(x,c) = self.rnn(x)
  33. x = x[-1]
  34. x = x.squeeze(0)
  35. return x.view(size[0], 1, 1, self.out_size)
  36. class EmbeddingLearner(nn.Module):
  37. def __init__(self):
  38. super(EmbeddingLearner, self).__init__()
  39. def forward(self, h, t, r, pos_num):
  40. score = -torch.norm(h + r - t, 2, -1).squeeze(2)
  41. p_score = score[:, :pos_num]
  42. n_score = score[:, pos_num:]
  43. return p_score, n_score
  44. def bpr_loss(p_scores, n_values,device):
  45. ratio = int(n_values.shape[1] / p_scores.shape[1])
  46. temp_pvalues = torch.tensor([],device=device)
  47. for i in range(p_scores.shape[1]):
  48. temp_pvalues = torch.cat((temp_pvalues, p_scores[:, i, None].expand(-1, ratio)), dim=1)
  49. d = torch.sub(temp_pvalues,n_values)
  50. t = F.logsigmoid(d)
  51. loss = -1 * (1.0/n_values.shape[1]) * t.sum(dim=1)
  52. loss = loss.sum(dim=0)
  53. return loss
  54. def bpr_max_loss(p_scores, n_values,device):
  55. s = F.softmax(n_values,dim=1)
  56. ratio = int(n_values.shape[1] / p_scores.shape[1])
  57. temp_pvalues = torch.tensor([],device=device)
  58. for i in range(p_scores.shape[1]):
  59. temp_pvalues = torch.cat((temp_pvalues,p_scores[:,i,None].expand(-1,ratio)),dim=1)
  60. d = torch.sigmoid(torch.sub(temp_pvalues,n_values))
  61. t = torch.mul(s,d)
  62. loss = -1 * torch.log(t.sum(dim=1))
  63. loss = loss.sum()
  64. return loss
  65. def top_loss(p_scores, n_values,device):
  66. ratio = int(n_values.shape[1] / p_scores.shape[1])
  67. temp_pvalues = torch.tensor([],device=device)
  68. for i in range(p_scores.shape[1]):
  69. temp_pvalues = torch.cat((temp_pvalues, p_scores[:, i, None].expand(-1, ratio)), dim=1)
  70. t1 = torch.sigmoid(torch.sub(n_values , temp_pvalues))
  71. t2 = torch.sigmoid(torch.pow(n_values,2))
  72. t = torch.add(t1,t2)
  73. t = t.sum(dim=1)
  74. loss = t / n_values.shape[1]
  75. loss = loss.sum(dim=0)
  76. return loss
  77. class MetaTL(nn.Module):
  78. def __init__(self, itemnum, parameter):
  79. super(MetaTL, self).__init__()
  80. # self.device = torch.device(parameter['device'])
  81. self.device = parameter['device']
  82. self.beta = parameter['beta']
  83. # self.dropout_p = parameter['dropout_p']
  84. self.embed_dim = parameter['embed_dim']
  85. self.margin = parameter['margin']
  86. self.embedding = Embedding(itemnum, parameter)
  87. self.relation_learner = MetaLearner(parameter['K'] - 1, embed_size=self.embed_dim, num_hidden1=500,
  88. num_hidden2=200, out_size=100, dropout_p=0)
  89. self.embedding_learner = EmbeddingLearner()
  90. # self.loss_func = nn.MarginRankingLoss(self.margin)
  91. self.loss_func = bpr_loss
  92. self.rel_q_sharing = dict()
  93. def split_concat(self, positive, negative):
  94. pos_neg_e1 = torch.cat([positive[:, :, 0, :],
  95. negative[:, :, 0, :]], 1).unsqueeze(2)
  96. pos_neg_e2 = torch.cat([positive[:, :, 1, :],
  97. negative[:, :, 1, :]], 1).unsqueeze(2)
  98. return pos_neg_e1, pos_neg_e2
  99. def forward(self, task, iseval=False, curr_rel=''):
  100. # transfer task string into embedding
  101. support, support_negative, query, negative = [self.embedding(t) for t in task]
  102. K = support.shape[1] # num of K
  103. num_sn = support_negative.shape[1] # num of support negative
  104. num_q = query.shape[1] # num of query
  105. num_n = negative.shape[1] # num of query negative
  106. rel = self.relation_learner(support)
  107. rel.retain_grad()
  108. rel_s = rel.expand(-1, K+num_sn, -1, -1)
  109. if iseval and curr_rel != '' and curr_rel in self.rel_q_sharing.keys():
  110. rel_q = self.rel_q_sharing[curr_rel]
  111. else:
  112. sup_neg_e1, sup_neg_e2 = self.split_concat(support, support_negative)
  113. p_score, n_score = self.embedding_learner(sup_neg_e1, sup_neg_e2, rel_s, K)
  114. # y = torch.Tensor([1]).to(self.device)
  115. self.zero_grad()
  116. # sorted,indecies = torch.sort(n_score, descending=True,dim=1)
  117. # n_values = sorted[:,0:p_score.shape[1]]
  118. # loss = self.loss_func(p_score, n_values, y)
  119. loss = self.loss_func(p_score,n_score,device=self.device)
  120. loss.backward(retain_graph=True)
  121. grad_meta = rel.grad
  122. rel_q = rel - self.beta*grad_meta
  123. self.rel_q_sharing[curr_rel] = rel_q
  124. rel_q = rel_q.expand(-1, num_q + num_n, -1, -1)
  125. que_neg_e1, que_neg_e2 = self.split_concat(query, negative)
  126. p_score, n_score = self.embedding_learner(que_neg_e1, que_neg_e2, rel_q, num_q)
  127. return p_score, n_score