-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathinteractions.py
236 lines (181 loc) · 6.86 KB
/
interactions.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
234
235
236
"""
Classes describing datasets of user-item interactions. Instances of these
are returned by dataset-fetching and dataset-processing functions.
"""
import numpy as np
import scipy.sparse as sp
class Interactions(object):
"""
Interactions object. Contains (at a minimum) pair of user-item
interactions. This is designed only for implicit feedback scenarios.
Parameters
----------
file_path: file contains (user,item,rating) triplets
user_map: dict of user mapping
item_map: dict of item mapping
"""
def __init__(self, file_path,
user_map=None,
item_map=None):
if not user_map and not item_map:
user_map = dict()
item_map = dict()
num_user = 0
num_item = 0
else:
num_user = len(user_map)
num_item = len(item_map)
user_ids = list()
item_ids = list()
# read users and items from file
with open(file_path, 'r') as fin:
for line in fin:
u, i, _ = line.strip().split()
user_ids.append(u)
item_ids.append(i)
# update user and item mapping
for u in user_ids:
if u not in user_map:
user_map[u] = num_user
num_user += 1
for i in item_ids:
if i not in item_map:
item_map[i] = num_item
num_item += 1
user_ids = np.array([user_map[u] for u in user_ids])
item_ids = np.array([item_map[i] for i in item_ids])
self.num_users = num_user
self.num_items = num_item
self.user_ids = user_ids
self.item_ids = item_ids
self.user_map = user_map
self.item_map = item_map
self.sequences = None
self.test_sequences = None
def __len__(self):
return len(self.user_ids)
def tocoo(self):
"""
Transform to a scipy.sparse COO matrix.
"""
row = self.user_ids
col = self.item_ids
data = np.ones(len(self))
return sp.coo_matrix((data, (row, col)),
shape=(self.num_users, self.num_items))
def tocsr(self):
"""
Transform to a scipy.sparse CSR matrix.
"""
return self.tocoo().tocsr()
def to_sequence(self, sequence_length=5, target_length=1):
"""
Transform to sequence form.
Valid subsequences of users' interactions are returned. For
example, if a user interacted with items [1, 2, 3, 4, 5, 6, 7, 8, 9], the
returned interactions matrix at sequence length 5 and target length 3
will be be given by:
sequences:
[[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7]]
targets:
[[6, 7],
[7, 8],
[8, 9]]
sequence for test (the last 'sequence_length' items of each user's sequence):
[[5, 6, 7, 8, 9]]
Parameters
----------
sequence_length: int
Sequence length. Subsequences shorter than this
will be left-padded with zeros.
target_length: int
Sequence target length.
"""
# change the item index start from 1 as 0 is used for padding in sequences
for k, v in self.item_map.items():
self.item_map[k] = v + 1
self.item_ids = self.item_ids + 1
self.num_items += 1
max_sequence_length = sequence_length + target_length
# Sort first by user id
sort_indices = np.lexsort((self.user_ids,))
user_ids = self.user_ids[sort_indices]
item_ids = self.item_ids[sort_indices]
user_ids, indices, counts = np.unique(user_ids,
return_index=True,
return_counts=True)
num_subsequences = sum([c - max_sequence_length + 1 if c >= max_sequence_length else 1 for c in counts])
sequences = np.zeros((num_subsequences, sequence_length),
dtype=np.int64)
sequences_targets = np.zeros((num_subsequences, target_length),
dtype=np.int64)
sequence_users = np.empty(num_subsequences,
dtype=np.int64)
test_sequences = np.zeros((self.num_users, sequence_length),
dtype=np.int64)
test_users = np.empty(self.num_users,
dtype=np.int64)
_uid = None
for i, (uid,
item_seq) in enumerate(_generate_sequences(user_ids,
item_ids,
indices,
max_sequence_length)):
if uid != _uid:
test_sequences[uid][:] = item_seq[-sequence_length:]
test_users[uid] = uid
_uid = uid
sequences_targets[i][:] = item_seq[-target_length:]
sequences[i][:] = item_seq[:sequence_length]
sequence_users[i] = uid
self.sequences = SequenceInteractions(sequence_users, sequences, sequences_targets)
self.test_sequences = SequenceInteractions(test_users, test_sequences)
class SequenceInteractions(object):
"""
Interactions encoded as a sequence matrix.
Parameters
----------
user_ids: np.array
sequence users
sequences: np.array
The interactions sequence matrix, as produced by
:func:`~Interactions.to_sequence`
targets: np.array
sequence targets
"""
def __init__(self,
user_ids,
sequences,
targets=None):
self.user_ids = user_ids
self.sequences = sequences
self.targets = targets
self.L = sequences.shape[1]
self.T = None
if np.any(targets):
self.T = targets.shape[1]
def _sliding_window(tensor, window_size, step_size=1):
if len(tensor) - window_size >= 0:
for i in range(len(tensor), 0, -step_size):
if i - window_size >= 0:
yield tensor[i - window_size:i]
else:
break
else:
num_paddings = window_size - len(tensor)
# Pad sequence with 0s if it is shorter than windows size.
yield np.pad(tensor, (num_paddings, 0), 'constant')
def _generate_sequences(user_ids, item_ids,
indices,
max_sequence_length):
for i in range(len(indices)):
start_idx = indices[i]
if i >= len(indices) - 1:
stop_idx = None
else:
stop_idx = indices[i + 1]
for seq in _sliding_window(item_ids[start_idx:stop_idx],
max_sequence_length):
yield (user_ids[i], seq)