|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +import torch.nn.functional as F |
| 4 | +import dgl.function as fn |
| 5 | + |
| 6 | +class NGCFLayer(nn.Module): |
| 7 | + def __init__(self, in_size, out_size, norm_dict, dropout): |
| 8 | + super(NGCFLayer, self).__init__() |
| 9 | + self.in_size = in_size |
| 10 | + self.out_size = out_size |
| 11 | + |
| 12 | + #weights for different types of messages |
| 13 | + self.W1 = nn.Linear(in_size, out_size, bias = True) |
| 14 | + self.W2 = nn.Linear(in_size, out_size, bias = True) |
| 15 | + |
| 16 | + #leaky relu |
| 17 | + self.leaky_relu = nn.LeakyReLU(0.2) |
| 18 | + |
| 19 | + #dropout layer |
| 20 | + self.dropout = nn.Dropout(dropout) |
| 21 | + |
| 22 | + #initialization |
| 23 | + torch.nn.init.xavier_uniform_(self.W1.weight) |
| 24 | + torch.nn.init.constant_(self.W1.bias, 0) |
| 25 | + torch.nn.init.xavier_uniform_(self.W2.weight) |
| 26 | + torch.nn.init.constant_(self.W2.bias, 0) |
| 27 | + |
| 28 | + #norm |
| 29 | + self.norm_dict = norm_dict |
| 30 | + |
| 31 | + def forward(self, g, feat_dict): |
| 32 | + |
| 33 | + funcs = {} #message and reduce functions dict |
| 34 | + #for each type of edges, compute messages and reduce them all |
| 35 | + for srctype, etype, dsttype in g.canonical_etypes: |
| 36 | + if srctype == dsttype: #for self loops |
| 37 | + messages = self.W1(feat_dict[srctype]) |
| 38 | + g.nodes[srctype].data[etype] = messages #store in ndata |
| 39 | + funcs[(srctype, etype, dsttype)] = (fn.copy_u(etype, 'm'), fn.sum('m', 'h')) #define message and reduce functions |
| 40 | + else: |
| 41 | + src, dst = g.edges(etype=(srctype, etype, dsttype)) |
| 42 | + norm = self.norm_dict[(srctype, etype, dsttype)] |
| 43 | + messages = norm * (self.W1(feat_dict[srctype][src]) + self.W2(feat_dict[srctype][src]*feat_dict[dsttype][dst])) #compute messages |
| 44 | + g.edges[(srctype, etype, dsttype)].data[etype] = messages #store in edata |
| 45 | + funcs[(srctype, etype, dsttype)] = (fn.copy_e(etype, 'm'), fn.sum('m', 'h')) #define message and reduce functions |
| 46 | + |
| 47 | + g.multi_update_all(funcs, 'sum') #update all, reduce by first type-wisely then across different types |
| 48 | + feature_dict={} |
| 49 | + for ntype in g.ntypes: |
| 50 | + h = self.leaky_relu(g.nodes[ntype].data['h']) #leaky relu |
| 51 | + h = self.dropout(h) #dropout |
| 52 | + h = F.normalize(h,dim=1,p=2) #l2 normalize |
| 53 | + feature_dict[ntype] = h |
| 54 | + return feature_dict |
| 55 | + |
| 56 | +class NGCF(nn.Module): |
| 57 | + def __init__(self, g, in_size, layer_size, dropout, lmbd=1e-5): |
| 58 | + super(NGCF, self).__init__() |
| 59 | + self.lmbd = lmbd |
| 60 | + self.norm_dict = dict() |
| 61 | + for srctype, etype, dsttype in g.canonical_etypes: |
| 62 | + src, dst = g.edges(etype=(srctype, etype, dsttype)) |
| 63 | + dst_degree = g.in_degrees(dst, etype=(srctype, etype, dsttype)).float() #obtain degrees |
| 64 | + src_degree = g.out_degrees(src, etype=(srctype, etype, dsttype)).float() |
| 65 | + norm = torch.pow(src_degree * dst_degree, -0.5).unsqueeze(1) #compute norm |
| 66 | + self.norm_dict[(srctype, etype, dsttype)] = norm |
| 67 | + |
| 68 | + self.layers = nn.ModuleList() |
| 69 | + self.layers.append( |
| 70 | + NGCFLayer(in_size, layer_size[0], self.norm_dict, dropout[0]) |
| 71 | + ) |
| 72 | + self.num_layers = len(layer_size) |
| 73 | + for i in range(self.num_layers-1): |
| 74 | + self.layers.append( |
| 75 | + NGCFLayer(layer_size[i], layer_size[i+1], self.norm_dict, dropout[i+1]) |
| 76 | + ) |
| 77 | + self.initializer = nn.init.xavier_uniform_ |
| 78 | + |
| 79 | + #embeddings for different types of nodes |
| 80 | + self.feature_dict = nn.ParameterDict({ |
| 81 | + ntype: nn.Parameter(self.initializer(torch.empty(g.num_nodes(ntype), in_size))) for ntype in g.ntypes |
| 82 | + }) |
| 83 | + |
| 84 | + def create_bpr_loss(self, users, pos_items, neg_items): |
| 85 | + pos_scores = (users * pos_items).sum(1) |
| 86 | + neg_scores = (users * neg_items).sum(1) |
| 87 | + |
| 88 | + mf_loss = nn.LogSigmoid()(pos_scores - neg_scores).mean() |
| 89 | + mf_loss = -1 * mf_loss |
| 90 | + |
| 91 | + regularizer = (torch.norm(users) ** 2 + torch.norm(pos_items) ** 2 + torch.norm(neg_items) ** 2) / 2 |
| 92 | + emb_loss = self.lmbd * regularizer / users.shape[0] |
| 93 | + |
| 94 | + return mf_loss + emb_loss, mf_loss, emb_loss |
| 95 | + |
| 96 | + def rating(self, u_g_embeddings, pos_i_g_embeddings): |
| 97 | + return torch.matmul(u_g_embeddings, pos_i_g_embeddings.t()) |
| 98 | + |
| 99 | + def forward(self, g,user_key, item_key, users, pos_items, neg_items): |
| 100 | + h_dict = {ntype : self.feature_dict[ntype] for ntype in g.ntypes} |
| 101 | + #obtain features of each layer and concatenate them all |
| 102 | + user_embeds = [] |
| 103 | + item_embeds = [] |
| 104 | + user_embeds.append(h_dict[user_key]) |
| 105 | + item_embeds.append(h_dict[item_key]) |
| 106 | + for layer in self.layers: |
| 107 | + h_dict = layer(g, h_dict) |
| 108 | + user_embeds.append(h_dict[user_key]) |
| 109 | + item_embeds.append(h_dict[item_key]) |
| 110 | + user_embd = torch.cat(user_embeds, 1) |
| 111 | + item_embd = torch.cat(item_embeds, 1) |
| 112 | + |
| 113 | + u_g_embeddings = user_embd[users, :] |
| 114 | + pos_i_g_embeddings = item_embd[pos_items, :] |
| 115 | + neg_i_g_embeddings = item_embd[neg_items, :] |
| 116 | + |
| 117 | + return u_g_embeddings, pos_i_g_embeddings, neg_i_g_embeddings |
0 commit comments