-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinteractions.py
385 lines (330 loc) · 18.3 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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import numpy as np
import pandas as pd
import scipy.sparse as sp
import matchzoo
import collections
from setting_keywords import KeyWordSettings
from handlers.output_handler import FileHandler
def _laplacian_normalize(adj):
"""Symmetrically normalize adjacency matrix."""
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return (adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt)).A
class MatchInteraction(object):
"""
Interactions object. Contains (at a minimum) pair of user-item
interactions, but can also be enriched with ratings, timestamps,
and interaction weights.
For *implicit feedback* scenarios, user ids and item ids should
only be provided for user-item pairs where an interaction was
observed. All pairs that are not provided are treated as missing
observations, and often interpreted as (implicit) negative
signals.
For *explicit feedback* scenarios, user ids, item ids, and
ratings should be provided for all user-item-rating triplets
that were observed in the dataset.
This class is designed specificlaly for matching models only. Since I don't want
to use MatchZoo datapack at all.
Parameters
----------
data_pack:
Attributes
----------
unique_query_ids: `np.ndarray`array of np.int32
array of user ids of the user-item pairs
query_contents: array of np.int32
array of item ids of the user-item pairs
query_lengths: array of np.float32, optional
array of ratings
unique_doc_ids: array of np.int32, optional
array of timestamps
doc_contents: array of np.float32, optional
array of weights
doc_lengths: int, optional
Number of distinct users in the dataset.
pos_queries: list[int]
Number of distinct items in the dataset.
pos_docs: list[int]
Number of distinct items in the dataset.
negatives: dict
"""
def __init__(self, data_pack: matchzoo.DataPack, **kargs):
# Note that, these indices are not from 0.
FileHandler.myprint("Converting DataFrame to Normal Dictionary of Data")
self.unique_query_ids, \
self.dict_query_contents, \
self.dict_query_lengths, \
self.dict_query_raw_contents, \
self.dict_query_positions = self.convert_leftright(data_pack.left, text_key="text_left",
length_text_key="length_left",
raw_text_key="raw_text_left")
self.data_pack = data_pack
assert len(self.unique_query_ids) == len(set(self.unique_query_ids)), "Must be unique ids"
""" Why do I need to sort it? I have no idea why did I do it? """
self.unique_doc_ids, \
self.dict_doc_contents, \
self.dict_doc_lengths, \
self.dict_doc_raw_contents, \
self.dict_doc_positions = self.convert_leftright(data_pack.right, text_key="text_right",
length_text_key="length_right",
raw_text_key="raw_text_right")
assert len(self.unique_doc_ids) == len(set(self.unique_doc_ids)), "Must be unique ids for doc ids"
assert len(self.unique_query_ids) != len(
self.unique_doc_ids), "Impossible to have equal number of docs and number of original tweets"
self.pos_queries, \
self.pos_docs, \
self.negatives, \
self.unique_queries_test = self.convert_relations(data_pack.relation)
# for queries, padded
self.np_query_contents = np.array([self.dict_query_contents[q] for q in self.pos_queries])
self.np_query_lengths = np.array([self.dict_query_lengths[q] for q in self.pos_queries])
self.query_positions = np.array([self.dict_query_positions[q] for q in self.pos_queries])
# for docs, padded
self.np_doc_contents = np.array([self.dict_doc_contents[d] for d in self.pos_docs])
self.np_doc_lengths = np.array([self.dict_doc_lengths[d] for d in self.pos_docs])
self.doc_positions = np.array([self.dict_doc_positions[d] for d in self.pos_docs])
assert self.np_query_lengths.shape == self.np_doc_lengths.shape
self.padded_doc_length = len(self.np_doc_contents[0])
self.padded_query_length = len(self.np_query_contents[0])
def convert_leftright(self, part: pd.DataFrame, text_key: str, length_text_key: str, raw_text_key: str, **kargs):
""" Converting the dataframe of interactions """
ids, contents_dict, lengths_dict, position_dict = [], {}, {}, {}
raw_content_dict = {}
# Why don't we use the queryID as the key for dictionary????
FileHandler.myprint("[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, "
"therefore, iterrows will return index which is left_id or right_id")
for index, row in part.iterrows(): # very dangerous, be careful because it may change order!!!
ids.append(index)
text_ = row[text_key] # text_ here is converted to numbers and padded
raw_content_dict[index] = row[raw_text_key]
if length_text_key not in row:
length_ = len(text_)
else:
length_ = row[length_text_key]
assert length_ != 0
assert index not in contents_dict
contents_dict[index] = text_
lengths_dict[index] = length_
position_dict[index] = np.pad(np.arange(length_) + 1, (0, len(text_) - length_), 'constant')
return np.array(ids), contents_dict, lengths_dict, raw_content_dict, position_dict
def convert_relations(self, relation: pd.DataFrame):
""" Convert relations.
We want to retrieve positive interactions and negative interactions. Particularly,
for every pair (query, doc) = 1, we get a list of negatives of the query q
It is possible that a query may have multiple positive docs. Therefore, negatives[q]
may vary the lengths but not too much.
"""
queries, docs, negatives = [], [], collections.defaultdict(list)
unique_queries = collections.defaultdict(list)
for index, row in relation.iterrows():
query = row["id_left"]
doc = row["id_right"]
label = row["label"]
assert label == 0 or label == 1
unique_queries[query] = unique_queries.get(query, [[], [], [], []]) # doc, label, content, length
a, b, c, d = unique_queries[query]
a.append(doc)
b.append(label)
c.append(self.dict_doc_contents[doc])
d.append(self.dict_doc_lengths[doc])
if label == 1:
queries.append(query)
docs.append(doc)
elif label == 0:
negatives[query].append(doc)
assert len(queries) == len(docs)
return np.array(queries), np.array(docs), negatives, unique_queries
def __repr__(self):
return ('<Interactions dataset ({num_users} users x {num_items} items '
'x {num_interactions} interactions)>'
.format(
num_users=self.num_users,
num_items=self.num_items,
num_interactions=len(self)
))
def _check(self):
pass
class BaseClassificationInteractions(object):
""" Base classification interactions for fact-checking with evidences """
def __init__(self, data_pack: matchzoo.DataPack, **kargs):
# FileHandler.myprint("Converting DataFrame to Normal Dictionary of Data")
self.output_handler = kargs[KeyWordSettings.OutputHandlerFactChecking]
self.output_handler.myprint("Converting DataFrame to Normal Dictionary of Data")
additional_field = {KeyWordSettings.FCClass.CharSourceKey: "char_claim_source",
KeyWordSettings.GNN_Window: kargs[KeyWordSettings.GNN_Window]}
self.unique_query_ids, \
self.dict_claim_contents, \
self.dict_claim_lengths, \
self.dict_query_raw_contents, \
self.dict_query_positions, \
self.dict_claim_source, \
self.dict_raw_claim_source, \
self.dict_char_left_src, \
self.dict_query_adj = self.convert_leftright(data_pack.left, text_key="text_left",
length_text_key="length_left", raw_text_key="raw_text_left",
source_key="claim_source", raw_source_key="raw_claim_source",
**additional_field)
self.data_pack = data_pack
assert len(self.unique_query_ids) == len(set(self.unique_query_ids)), "Must be unique ids"
""" Why do I need to sort it? I have no idea why did I do it? """
additional_field = {KeyWordSettings.FCClass.CharSourceKey: "char_evidence_source",
KeyWordSettings.GNN_Window: kargs[KeyWordSettings.GNN_Window]}
self.unique_doc_ids, \
self.dict_doc_contents, \
self.dict_doc_lengths, \
self.dict_doc_raw_contents, \
self.dict_doc_positions, \
self.dict_evd_source, \
self.dict_raw_evd_source, \
self.dict_char_right_src, \
self.dict_doc_adj = self.convert_leftright(data_pack.right, text_key="text_right",
length_text_key="length_right",
raw_text_key="raw_text_right", source_key="evidence_source",
raw_source_key="raw_evidence_source", **additional_field)
assert len(self.unique_doc_ids) == len(set(self.unique_doc_ids)), "Must be unique ids for doc ids"
assert len(self.unique_query_ids) != len(
self.unique_doc_ids), "Impossible to have equal number of docs and number of original tweets"
def convert_leftright(self, part: pd.DataFrame, text_key: str, length_text_key: str, raw_text_key: str,
source_key: str, raw_source_key: str, **kargs):
""" Converting the dataframe of interactions """
ids, contents_dict, lengths_dict, position_dict = [], {}, {}, {}
raw_content_dict, sources, raw_sources, char_sources = {}, {}, {}, {}
dict_adj = {}
fixed_length = 30 if text_key == 'text_left' else 100
char_source_key = kargs[KeyWordSettings.FCClass.CharSourceKey]
# Why don't we use the queryID as the key for dictionary????
self.output_handler.myprint("[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, "
"therefore, iterrows will return index which is left_id or right_id")
flag = False
for index, row in part.iterrows(): # very dangerous, be careful because it may change order!!!
ids.append(index)
text_ = row[text_key] # text_ here is converted to numbers and padded
raw_content_dict[index] = row[raw_text_key]
if flag is False:
print(text_)
flag=True
if length_text_key not in row:
length_ = len(text_)
else:
length_ = row[length_text_key]
assert length_ != 0
assert index not in contents_dict
contents_dict[index] = text_
lengths_dict[index] = length_
position_dict[index] = np.pad(np.arange(length_) + 1, (0, len(text_) - length_), 'constant')
sources[index] = row[source_key]
raw_sources[index] = row[raw_source_key]
char_sources[index] = row[char_source_key]
# calculate the adj in list type
adj = [[1 if ((i - 2 <= j <= i + 2 or text_[i] == text_[j]) and max(i, j) < length_) else 0
for j in range(fixed_length)] for i in range(fixed_length)]
dict_adj[index] = adj
return np.array(ids), contents_dict, lengths_dict, raw_content_dict, \
position_dict, sources, raw_sources, char_sources, dict_adj
def convert_relations(self, relation: pd.DataFrame):
pass
class ClassificationInteractions(BaseClassificationInteractions):
"""
This class is for classification based on evidences with GAT.
# Modified by: Junfei Wu. 2021/9/13 14:57
Query - [list of evidences] -> labels
"""
def __init__(self, data_pack: matchzoo.DataPack, **kargs):
super(ClassificationInteractions, self).__init__(data_pack, **kargs)
# (1) unique claims, (2) labels for each claim and (3) info of each claim
self.claims, self.claims_labels, self.dict_claims_and_evidences_test = \
self.convert_relations(data_pack.relation)
# for queries, padded
self.np_query_contents = np.array([self.dict_claim_contents[q] for q in self.claims])
self.np_query_lengths = np.array([self.dict_claim_lengths[q] for q in self.claims])
self.np_query_char_source = np.array([self.dict_char_left_src[q] for q in self.claims])
self.query_positions = np.array([self.dict_query_positions[q] for q in self.claims])
self.np_query_adj = np.array([self.dict_query_adj[q] for q in self.claims]) # query_adj matrix
# assert self.np_query_lengths.shape == self.np_doc_lengths.shape
self.padded_doc_length = len(self.dict_doc_contents[self.unique_doc_ids[0]])
self.padded_doc_char_source_length = len(self.dict_char_right_src[self.unique_doc_ids[0]])
# self.padded_query_length = len(self.np_query_contents[0])
def convert_leftright(self, part: pd.DataFrame, text_key: str, length_text_key: str, raw_text_key: str,
source_key: str, raw_source_key: str, **kargs):
""" Converting the dataframe of interactions
Compress the text & build GAT adjacent matrix
"""
ids, contents_dict, lengths_dict, position_dict = [], {}, {}, {}
raw_content_dict, sources, raw_sources, char_sources = {}, {}, {}, {}
dict_adj = {}
fixed_length = 30 if text_key == 'text_left' else 100
char_source_key = kargs[KeyWordSettings.FCClass.CharSourceKey]
# Why don't we use the queryID as the key for dictionary????
self.output_handler.myprint("[NOTICE] MatchZoo use queryID and docID as index in dataframe left and right, "
"therefore, iterrows will return index which is left_id or right_id")
for index, row in part.iterrows(): # very dangerous, be careful because it may change order!!!
ids.append(index)
text_, adj, length_ = self.convert_text(row[text_key], fixed_length, row[length_text_key],
kargs[KeyWordSettings.GNN_Window])
# if fixed_length==100:
# # contain raw text to lstm
# text_ = row[text_key] # text_ here is converted to numbers and padded
# if length_text_key not in row:
# length_ = len(text_)
# else:
# length_ = row[length_text_key]
raw_content_dict[index] = row[raw_text_key] # origin text
assert length_ != 0
assert index not in contents_dict
contents_dict[index] = text_
lengths_dict[index] = length_
position_dict[index] = np.pad(np.arange(length_) + 1, (0, len(text_) - length_), 'constant')
sources[index] = row[source_key]
raw_sources[index] = row[raw_source_key]
char_sources[index] = row[char_source_key]
dict_adj[index] = adj
return np.array(ids), contents_dict, lengths_dict, raw_content_dict, \
position_dict, sources, raw_sources, char_sources, dict_adj
def convert_text(self, raw_text, fixed_length, length, window_size=5):
words_list = list(set(raw_text[:length])) # remove duplicate words in original order
words_list.sort(key=raw_text.index)
words2id = {word: id for id, word in enumerate(words_list)}
length_ = len(words2id)
neighbours = [set() for _ in range(length_)]
# window_size = window_size if fixed_length == 30 else 300
for i, word in enumerate(raw_text[:length]):
for j in range(max(i-window_size+1, 0), min(i+window_size, length)):
neighbours[words2id[word]].add(words2id[raw_text[j]])
# gat graph
adj = [[1 if (max(i, j) < length_) and (j in neighbours[i]) else 0 for j in range(fixed_length)]
for i in range(fixed_length)]
words_list.extend([0 for _ in range(fixed_length-length_)])
adj = _laplacian_normalize(np.array(adj))
return words_list, adj, length_
def convert_relations(self, relation: pd.DataFrame):
""" Convert relations.
We want to retrieve positive interactions and negative interactions. Particularly,
for every pair (query, doc) = 1, we get a list of negatives of the query q
It is possible that a query may have multiple positive docs. Therefore, negatives[q]
may vary the lengths but not too much.
"""
queries = [] # , collections.defaultdict(list)
queries_labels = []
unique_queries = collections.defaultdict(list)
set_queries = set()
for index, row in relation.iterrows():
query = row["id_left"]
doc = row["id_right"]
label = row["label"]
# assert label == 0 or label == 1
unique_queries[query] = unique_queries.get(query, [[], [], [], [], []]) # doc, label, content, length
a, b, c, d, e = unique_queries[query]
a.append(doc)
b.append(label)
c.append(self.dict_doc_contents[doc])
d.append(self.dict_doc_lengths[doc])
e.append(self.dict_doc_adj[doc])
if query not in set_queries:
queries.append(query) # same as unique_queries
queries_labels.append(label)
set_queries.add(query)
assert len(queries) == len(unique_queries)
return np.array(queries), np.array(queries_labels), unique_queries