-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
295 lines (219 loc) · 9.04 KB
/
parser.py
File metadata and controls
295 lines (219 loc) · 9.04 KB
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
import os.path
import pickle as pkl
import numpy as np
import scipy.sparse as sps
import gzip
def open_file(filename):
file = None
if os.path.isfile(filename):
file = open(filename, "r")
elif os.path.isfile(filename + ".gz"):
file = gzip.open(filename + ".gz", "rt")
return file
def read_parse_save(folder, threshold=0., binarize=False, force_user_merge=False):
print("Working on {}".format(folder))
has_test = os.path.isfile(folder + "/test_run.tsv") or os.path.isfile(folder + "/test_run.tsv.gz")
user_mapping = {}
item_mapping = {}
urm_row = []
urm_col = []
urm_data = []
urm_binary_data = []
file = open_file(folder + "/train.tsv")
if file is not None:
jump_header = True
for line in file:
if jump_header:
jump_header = False
continue
split_row = line.strip().split("\t")
uname = split_row[0].strip()
iname = split_row[1].strip()
rating = float(split_row[2].strip())
if force_user_merge:
uname = uname[2:]
if rating < threshold:
rating = 0.
if uname in user_mapping.keys():
uid = user_mapping[uname]
else:
uid = len(user_mapping)
user_mapping[uname] = uid
if iname in item_mapping.keys():
iid = item_mapping[iname]
else:
iid = len(item_mapping)
item_mapping[iname] = iid
if rating > 0.:
urm_row.append(uid)
urm_col.append(iid)
urm_data.append(rating)
urm_binary_data.append(1.)
file.close()
file = open_file(folder + "/train_5core.tsv")
if file is not None:
jump_header = True
for line in file:
if jump_header:
jump_header = False
continue
split_row = line.strip().split("\t")
uname = split_row[0].strip()
iname = split_row[1].strip()
if force_user_merge:
uname = uname[2:]
if uname in user_mapping.keys():
uid = user_mapping[uname]
else:
uid = len(user_mapping)
user_mapping[uname] = uid
if iname in item_mapping.keys():
iid = item_mapping[iname]
else:
iid = len(item_mapping)
item_mapping[iname] = iid
urm_row.append(uid)
urm_col.append(iid)
urm_data.append(4.)
urm_binary_data.append(1.)
file.close()
urm_valid_row = []
urm_valid_col = []
urm_valid_data = []
userset = set()
file = open_file(folder + "/valid_qrel.tsv")
if file is not None:
jump_header = True
for line in file:
if jump_header:
jump_header = False
continue
split_row = line.strip().split("\t")
uname = split_row[0].strip()
iname = split_row[1].strip()
if force_user_merge:
uname = uname[2:]
if uname in user_mapping.keys():
uid = user_mapping[uname]
else:
uid = len(user_mapping)
user_mapping[uname] = uid
if iname in item_mapping.keys():
iid = item_mapping[iname]
else:
iid = len(item_mapping)
item_mapping[iname] = iid
if uid in userset:
# Only one interaction in validation/test per user
continue
userset.add(uid)
urm_valid_row.append(uid)
urm_valid_col.append(iid)
urm_valid_data.append(float(split_row[2].strip()))
file.close()
urm_valid_neg_row = []
urm_valid_neg_col = []
userset = set()
file = open_file(folder + "/valid_run.tsv")
if file is not None:
for line in file:
split_row = line.strip().split("\t")
uname = split_row[0].strip()
if force_user_merge:
uname = uname[2:]
if uname in user_mapping.keys():
uid = user_mapping[uname]
else:
uid = len(user_mapping)
user_mapping[uname] = uid
if uid in userset:
# Only one interaction in validation/test per user
continue
userset.add(uid)
for iname in split_row[1].strip().split(","):
iname = iname.strip()
if iname in item_mapping.keys():
iid = item_mapping[iname]
else:
iid = len(item_mapping)
item_mapping[iname] = iid
urm_valid_neg_row.append(uid)
urm_valid_neg_col.append(iid)
file.close()
if has_test:
urm_test_neg_row = []
urm_test_neg_col = []
file = open_file(folder + "/test_run.tsv")
if file is not None:
for line in file:
split_row = line.strip().split("\t")
uname = split_row[0].strip()
if force_user_merge:
uname = uname[2:]
if uname in user_mapping.keys():
uid = user_mapping[uname]
else:
uid = len(user_mapping)
user_mapping[uname] = uid
for iname in split_row[1].split(","):
iname = iname.strip()
if iname in item_mapping.keys():
iid = item_mapping[iname]
else:
iid = len(item_mapping)
item_mapping[iname] = iid
urm_test_neg_row.append(uid)
urm_test_neg_col.append(iid)
file.close()
n_users = len(user_mapping)
n_items = len(item_mapping)
urm = sps.csr_matrix((urm_data, (urm_row, urm_col)), shape=(n_users, n_items), dtype=np.float32)
urm.eliminate_zeros()
urm.sort_indices()
binary_urm = sps.csr_matrix((urm_binary_data, (urm_row, urm_col)), shape=(n_users, n_items), dtype=np.float32)
binary_urm.eliminate_zeros()
binary_urm.sort_indices()
binary_urm = binary_urm.tocoo()
for i in range(len(binary_urm.data)):
if binary_urm.data[i] > 1.:
urm[binary_urm.row[i], binary_urm.col[i]] /= binary_urm.data[i]
del binary_urm
if binarize:
urm.data[:] = 1.
print("urm", urm.shape, len(urm.data))
sps.save_npz(folder + "/urm.npz", urm, compressed=True)
urm_valid = sps.csr_matrix((urm_valid_data, (urm_valid_row, urm_valid_col)), shape=(n_users, n_items), dtype=np.float32)
urm_valid.eliminate_zeros()
urm_valid.sort_indices()
if binarize:
urm_valid.data[:] = 1.
print("urm_valid", urm_valid.shape, len(urm_valid.data))
sps.save_npz(folder + "/urm_valid.npz", urm_valid, compressed=True)
urm_valid_neg = sps.csr_matrix((np.ones(len(urm_valid_neg_row)), (urm_valid_neg_row, urm_valid_neg_col)), shape=(n_users, n_items), dtype=np.float32)
urm_valid_neg.eliminate_zeros()
urm_valid_neg.sort_indices()
print("urm_valid_neg", urm_valid_neg.shape, len(urm_valid_neg.data))
sps.save_npz(folder + "/urm_valid_neg.npz", urm_valid_neg, compressed=True)
# Small check: all positive items in validation have to be in items to rank for that user
users_to_recommend = np.arange(urm_valid.shape[0])[np.ediff1d(urm_valid.indptr) > 0]
for u in users_to_recommend:
assert np.all(np.isin(
urm_valid.indices[urm_valid.indptr[u]:urm_valid.indptr[u+1]],
urm_valid_neg.indices[urm_valid_neg.indptr[u]:urm_valid_neg.indptr[u+1]]
)), "Validation item for user {} not in items to rank".format(u)
if has_test:
urm_test_neg = sps.csr_matrix((np.ones(len(urm_test_neg_row)), (urm_test_neg_row, urm_test_neg_col)), shape=(n_users, n_items), dtype=np.float32)
urm_test_neg.eliminate_zeros()
urm_test_neg.sort_indices()
print("urm_test_neg", urm_test_neg.shape, len(urm_test_neg.data))
sps.save_npz(folder + "/urm_test_neg.npz", urm_test_neg, compressed=True)
with open(folder + "/user_mapping.pkl", "wb") as handle:
pkl.dump(user_mapping, handle, protocol=pkl.HIGHEST_PROTOCOL)
with open(folder + "/item_mapping.pkl", "wb") as handle:
pkl.dump(item_mapping, handle, protocol=pkl.HIGHEST_PROTOCOL)
print("-----------------")
if __name__ == "__main__":
for subdir in os.listdir("datasets"):
dir = "datasets" + os.sep + subdir
if os.path.isdir(dir) and ("t1" in dir or "t2" in dir) and "t1t2" not in dir:
read_parse_save(dir)