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 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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.es = parameter['embed_dim']
  10. self.embedding = nn.Embedding(num_ent + 1, self.es)
  11. nn.init.xavier_uniform_(self.embedding.weight)
  12. def forward(self, triples):
  13. idx = [[[t[0], t[2]] for t in batch] for batch in triples]
  14. idx = torch.LongTensor(idx).to(self.device)
  15. return self.embedding(idx)
  16. class MetaLearner(nn.Module):
  17. def __init__(self, K, embed_size=100, num_hidden1=500, num_hidden2=200, out_size=100, dropout_p=0.5):
  18. super(MetaLearner, self).__init__()
  19. self.embed_size = embed_size
  20. self.K = K
  21. # self.out_size = out_size
  22. # self.hidden_size = out_size
  23. self.out_size = embed_size
  24. self.hidden_size = embed_size
  25. self.rnn = nn.LSTM(embed_size,self.hidden_size,2,dropout=0.2)
  26. # nn.init.xavier_normal_(self.rnn.all_weights)
  27. def forward(self, inputs):
  28. size = inputs.shape
  29. x = torch.stack([inputs[:,0,0,:],inputs[:,0,1,:],inputs[:,1,1,:]],dim=1)
  30. x = x.transpose(0,1)
  31. _,(x,c) = self.rnn(x)
  32. x = x[-1]
  33. x = x.squeeze(0)
  34. return x.view(size[0], 1, 1, self.out_size)
  35. class EmbeddingLearner(nn.Module):
  36. def __init__(self):
  37. super(EmbeddingLearner, self).__init__()
  38. def forward(self, h, t, r, pos_num):
  39. score = -torch.norm(h + r - t, 2, -1).squeeze(2)
  40. p_score = score[:, :pos_num]
  41. n_score = score[:, pos_num:]
  42. return p_score, n_score
  43. class MetaTL(nn.Module):
  44. def __init__(self, itemnum, parameter):
  45. super(MetaTL, self).__init__()
  46. self.device = torch.device('cuda:0')
  47. self.beta = parameter['beta']
  48. # self.dropout_p = parameter['dropout_p']
  49. self.embed_dim = parameter['embed_dim']
  50. self.margin = parameter['margin']
  51. self.embedding = Embedding(itemnum, parameter)
  52. self.relation_learner = MetaLearner(parameter['K'] - 1, embed_size=self.embed_dim, num_hidden1=500,
  53. num_hidden2=200, out_size=100, dropout_p=0)
  54. self.embedding_learner = EmbeddingLearner()
  55. self.loss_func = nn.MarginRankingLoss(self.margin)
  56. self.rel_q_sharing = dict()
  57. def split_concat(self, positive, negative):
  58. pos_neg_e1 = torch.cat([positive[:, :, 0, :],
  59. negative[:, :, 0, :]], 1).unsqueeze(2)
  60. pos_neg_e2 = torch.cat([positive[:, :, 1, :],
  61. negative[:, :, 1, :]], 1).unsqueeze(2)
  62. return pos_neg_e1, pos_neg_e2
  63. def forward(self, task, iseval=False, curr_rel=''):
  64. # transfer task string into embedding
  65. support, support_negative, query, negative = [self.embedding(t) for t in task]
  66. K = support.shape[1] # num of K
  67. num_sn = support_negative.shape[1] # num of support negative
  68. num_q = query.shape[1] # num of query
  69. num_n = negative.shape[1] # num of query negative
  70. rel = self.relation_learner(support)
  71. rel.retain_grad()
  72. rel_s = rel.expand(-1, K+num_sn, -1, -1)
  73. if iseval and curr_rel != '' and curr_rel in self.rel_q_sharing.keys():
  74. rel_q = self.rel_q_sharing[curr_rel]
  75. else:
  76. sup_neg_e1, sup_neg_e2 = self.split_concat(support, support_negative)
  77. p_score, n_score = self.embedding_learner(sup_neg_e1, sup_neg_e2, rel_s, K)
  78. y = torch.Tensor([1]).to(self.device)
  79. self.zero_grad()
  80. loss = self.loss_func(p_score, n_score, y)
  81. loss.backward(retain_graph=True)
  82. grad_meta = rel.grad
  83. rel_q = rel - self.beta*grad_meta
  84. self.rel_q_sharing[curr_rel] = rel_q
  85. rel_q = rel_q.expand(-1, num_q + num_n, -1, -1)
  86. que_neg_e1, que_neg_e2 = self.split_concat(query, negative)
  87. p_score, n_score = self.embedding_learner(que_neg_e1, que_neg_e2, rel_q, num_q)
  88. return p_score, n_score