forked from RUCAIBox/RecBole-CDR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemcdr.py
233 lines (196 loc) · 10.6 KB
/
emcdr.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
# -*- coding: utf-8 -*-
# @Time : 2022/4/8
# @Author : Gaowei Zhang
# @Email : [email protected]
r"""
EMCDR
################################################
Reference:
Tong Man et al. "Cross-Domain Recommendation: An Embedding and Mapping Approach" in IJCAI 2017.
"""
import torch
import torch.nn as nn
from recbole.model.init import xavier_normal_initialization
from recbole.model.loss import EmbLoss
from recbole.model.loss import BPRLoss
from recbole.utils import InputType
from recbole_cdr.model.crossdomain_recommender import CrossDomainRecommender
class EMCDR(CrossDomainRecommender):
r"""EMCDR learns an mapping function from source latent space
to target latent space.
"""
def __init__(self, config, dataset):
super(EMCDR, self).__init__(config, dataset)
assert self.overlapped_num_items == 1 or self.overlapped_num_users == 1, \
"EMCDR model only support user overlapped or item overlapped dataset! "
if self.overlapped_num_users > 1:
self.mode = 'overlap_users'
elif self.overlapped_num_items > 1:
self.mode = 'overlap_items'
else:
self.mode = 'non_overlap'
self.phase = 'both'
# load parameters info
self.latent_factor_model = config['latent_factor_model']
if self.latent_factor_model == 'MF':
input_type = InputType.POINTWISE
# load dataset info
self.SOURCE_LABEL = dataset.source_domain_dataset.label_field
self.TARGET_LABEL = dataset.target_domain_dataset.label_field
self.loss = nn.MSELoss()
else:
input_type = InputType.PAIRWISE
# load dataset info
self.loss = BPRLoss()
self.source_latent_dim = config['source_embedding_size'] # int type:the embedding size of source latent space
self.target_latent_dim = config['target_embedding_size'] # int type:the embedding size of target latent space
self.reg_weight = config['reg_weight'] # float32 type: the weight decay for l2 normalization
self.map_func = config['mapping_function']
if self.map_func == 'linear':
self.mapping = nn.Linear(self.source_latent_dim, self.target_latent_dim, bias=False)
else:
assert config["mlp_hidden_size"] is not None
mlp_layers_dim = [self.source_latent_dim] + config["mlp_hidden_size"] + [self.target_latent_dim]
self.mapping = self.mlp_layers(mlp_layers_dim)
# define layers and loss
self.source_user_embedding = torch.nn.Embedding(self.total_num_users, self.source_latent_dim)
self.source_item_embedding = torch.nn.Embedding(self.total_num_items, self.source_latent_dim)
self.target_user_embedding = torch.nn.Embedding(self.total_num_users, self.target_latent_dim)
self.target_item_embedding = torch.nn.Embedding(self.total_num_items, self.target_latent_dim)
with torch.no_grad():
self.source_user_embedding.weight[self.overlapped_num_users: self.target_num_users].fill_(0)
self.source_item_embedding.weight[self.overlapped_num_items: self.target_num_items].fill_(0)
self.target_user_embedding.weight[self.target_num_users:].fill_(0)
self.target_item_embedding.weight[self.target_num_items:].fill_(0)
self.reg_loss = EmbLoss()
self.map_loss = nn.MSELoss()
# parameters initialization
self.apply(xavier_normal_initialization)
def mlp_layers(self, layer_dims):
mlp_modules = []
for i, (d_in, d_out) in enumerate(zip(layer_dims[:-1], layer_dims[1:])):
mlp_modules.append(nn.Linear(d_in, d_out))
if i != len(layer_dims[:-1]) - 1:
mlp_modules.append(nn.Tanh())
return nn.Sequential(*mlp_modules)
def set_phase(self, phase):
self.phase = phase
def source_forward(self, user, item):
user_e = self.source_user_embedding(user)
item_e = self.source_item_embedding(item)
return torch.mul(user_e, item_e).sum(dim=1)
def target_forward(self, user, item):
user_e = self.target_user_embedding(user)
item_e = self.target_item_embedding(item)
return torch.mul(user_e, item_e).sum(dim=1)
def calculate_source_loss(self, interaction):
if self.latent_factor_model == 'MF':
source_user = interaction[self.SOURCE_USER_ID]
source_item = interaction[self.SOURCE_ITEM_ID]
source_label = interaction[self.SOURCE_LABEL]
p_source = self.source_forward(source_user, source_item)
loss_s = self.loss(p_source, source_label) + \
self.reg_weight * self.reg_loss(self.source_user_embedding(source_user),
self.source_item_embedding(source_item))
else:
source_user = interaction[self.SOURCE_USER_ID]
source_pos_item = interaction[self.SOURCE_ITEM_ID]
source_neg_item = interaction[self.SOURCE_NEG_ITEM_ID]
pos_item_score = self.source_forward(source_user, source_pos_item)
neg_item_score = self.source_forward(source_user, source_neg_item)
loss_s = self.loss(pos_item_score, neg_item_score) + \
self.reg_weight * self.reg_loss(self.source_user_embedding(source_user),
self.source_item_embedding(source_pos_item))
return loss_s
def calculate_target_loss(self, interaction):
if self.latent_factor_model == 'MF':
target_user = interaction[self.TARGET_USER_ID]
target_item = interaction[self.TARGET_ITEM_ID]
target_label = interaction[self.TARGET_LABEL]
p_target = self.target_forward(target_user, target_item)
loss_t = self.loss(p_target, target_label) + \
self.reg_weight * self.reg_loss(self.target_user_embedding(target_user),
self.target_item_embedding(target_item))
else:
target_user = interaction[self.TARGET_USER_ID]
target_pos_item = interaction[self.TARGET_ITEM_ID]
target_neg_item = interaction[self.TARGET_NEG_ITEM_ID]
pos_item_score = self.target_forward(target_user, target_pos_item)
neg_item_score = self.target_forward(target_user, target_neg_item)
loss_t = self.loss(pos_item_score, neg_item_score) + \
self.reg_weight * self.reg_loss(self.target_user_embedding(target_user),
self.target_item_embedding(target_pos_item))
return loss_t
def calculate_map_loss(self, interaction):
idx = interaction[self.OVERLAP_ID]
if self.mode == 'overlap_users':
source_user_e = self.source_user_embedding(idx)
target_user_e = self.target_user_embedding(idx)
map_e = self.mapping(source_user_e)
loss = self.map_loss(map_e, target_user_e)
else:
source_item_e = self.source_item_embedding(idx)
target_item_e = self.target_item_embedding(idx)
map_e = self.mapping(source_item_e)
loss = self.map_loss(map_e, target_item_e)
return loss
def calculate_loss(self, interaction):
if self.phase == 'SOURCE':
return self.calculate_source_loss(interaction)
elif self.phase == 'OVERLAP':
return self.calculate_map_loss(interaction)
else:
return self.calculate_target_loss(interaction)
def predict(self, interaction):
if self.phase == 'SOURCE':
user = interaction[self.SOURCE_USER_ID]
item = interaction[self.SOURCE_ITEM_ID]
user_e = self.source_user_embedding(user)
item_e = self.source_item_embedding(item)
score = torch.mul(user_e, item_e).sum(dim=1)
elif self.phase == 'TARGET':
user = interaction[self.TARGET_USER_ID]
item = interaction[self.TARGET_ITEM_ID]
user_e = self.target_user_embedding(user)
item_e = self.target_item_embedding(item)
score = torch.mul(user_e, item_e).sum(dim=1)
else:
user = interaction[self.TARGET_USER_ID]
item = interaction[self.TARGET_ITEM_ID]
if self.mode == 'overlap_users':
repeat_user = user.repeat(self.source_latent_dim, 1).transpose(0, 1)
user_e = torch.where(repeat_user < self.overlapped_num_users, self.mapping(self.source_user_embedding(user)),
self.target_user_embedding(user))
item_e = self.target_item_embedding(item)
else:
user_e = self.target_user_embedding(user)
repeat_item = item.repeat(self.source_latent_dim, 1).transpose(0, 1)
item_e = torch.where(repeat_item < self.overlapped_num_items, self.mapping(self.source_item_embedding(item)),
self.target_item_embedding(item))
score = torch.mul(user_e, item_e).sum(dim=1)
return score
def full_sort_predict(self, interaction):
if self.phase == 'SOURCE':
user = interaction[self.SOURCE_USER_ID]
user_e = self.source_user_embedding(user)
overlap_item_e = self.source_item_embedding.weight[:self.overlapped_num_items]
source_item_e = self.source_item_embedding.weight[self.target_num_items:]
all_item_e = torch.cat([overlap_item_e, source_item_e], dim=0)
elif self.phase == 'TARGET':
user = interaction[self.TARGET_USER_ID]
user_e = self.target_user_embedding(user)
all_item_e = self.target_item_embedding.weight[:self.target_num_items]
else:
user = interaction[self.TARGET_USER_ID]
if self.mode == 'overlap_users':
repeat_user = user.repeat(self.source_latent_dim, 1).transpose(0, 1)
user_e = torch.where(repeat_user < self.overlapped_num_users, self.mapping(self.source_user_embedding(user)),
self.target_user_embedding(user))
all_item_e = self.target_item_embedding.weight[:self.target_num_items]
else:
user_e = self.target_user_embedding(user)
overlap_item_e = self.mapping(self.source_item_embedding.weight[:self.overlapped_num_items])
target_item_e = self.target_item_embedding.weight[self.overlapped_num_items:self.target_num_items]
all_item_e = torch.cat([overlap_item_e, target_item_e], dim=0)
score = torch.matmul(user_e, all_item_e.transpose(0, 1))
return score.view(-1)