forked from JasonLee-22/TR-Rules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule_learning.py
365 lines (302 loc) · 12.3 KB
/
rule_learning.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
import os
import json
import itertools
import numpy as np
from collections import Counter
import operator
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
class Rule_Learner(object):
def __init__(self, edges, id2relation, inv_relation_id, dataset):
self.edges = edges
self.id2relation = id2relation
self.inv_relation_id = inv_relation_id
self.found_rules = []
self.rules_dict = dict()
self.output_dir = "../output/" + dataset + "/"
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
def create_rule(self, walk):
rule = dict()
rule["head_rel"] = int(walk["relations"][0])
rule["body_rels"] = [
self.inv_relation_id[x] for x in walk["relations"][1:][::-1]
]
rule["var_constraints"] = self.define_var_constraints(
walk["entities"][1:][::-1]
)
rule["acyclic"] = False
if rule not in self.found_rules:
self.found_rules.append(rule.copy())
(
rule["conf"],
rule["rule_supp"],
rule["body_supp"],
) = self.estimate_confidence(rule)
if rule["conf"]:
self.update_rules_dict(rule)
def create_acyclic(self, walk):
rule = dict()
rule["head_rel"] = int(walk["relations"][0])
rule["body_rels"] = [
int(walk["relations"][-1])
]
rule["var_constraints"] = []
rule["acyclic"] = True
rule["no_constraint"] = False
rule["constraint_tail"] = int(walk["entities"][-1])
rule["head_constraint"] = int(walk["entities"][1])
if rule not in self.found_rules:
self.found_rules.append(rule.copy())
(
rule["conf"],
rule["rule_supp"],
rule["body_supp"],
) = self.estimate_acyclic_confidence(rule)
if rule["conf"]:
self.update_rules_dict(rule)
def define_var_constraints(self, entities):
var_constraints = []
for ent in set(entities): #[x,y,x,z] (x,y,z) --> [[0, 2], [1]. [3]]
all_idx = [idx for idx, x in enumerate(entities) if x == ent]
var_constraints.append(all_idx)
var_constraints = [x for x in var_constraints if len(x) > 1]
return sorted(var_constraints)
def estimate_confidence(self, rule, num_samples=500, weight=1.0, s=3):
all_bodies = []
for _ in range(num_samples):
sample_successful, body_ents_tss = self.sample_body(
rule["body_rels"], rule["var_constraints"]
)
if sample_successful:
all_bodies.append(body_ents_tss)
all_bodies.sort()
unique_bodies = list(x for x, _ in itertools.groupby(all_bodies))
body_support = len(unique_bodies)
confidence, rule_support = 0, 0
if body_support:
rule_support = self.calculate_rule_support(unique_bodies, rule["head_rel"])
confidence = rule_support / (body_support + s)
confidence = round(confidence * weight, 6)
return confidence, rule_support, body_support
# X r b -> X r' a
#
def estimate_acyclic_confidence(self, rule, num_samples=500, weight_constraint=1.0, s=3):
all_bodies = []
for _ in range(num_samples):
sample_successful, body_ents_tss = self.sample_acyclic_body(
rule["body_rels"],
rule["constraint_tail"]
)
if sample_successful:
all_bodies.append(body_ents_tss)
all_bodies.sort()
unique_bodies = list(x for x, _ in itertools.groupby(all_bodies))
body_support = len(unique_bodies)
confidence, rule_support = 0, 0
if body_support:
rule_support = self.calculate_acyclic_rule_support(unique_bodies, rule["head_rel"], rule["head_constraint"])
confidence = rule_support / (body_support + s)
confidence = round(confidence * weight_constraint, 6)
return confidence, rule_support, body_support
def sample_body(self, body_rels, var_constraints):
sample_successful = True
body_ents_tss = []
cur_rel = body_rels[0]
rel_edges = self.edges[cur_rel]
next_edge = rel_edges[np.random.choice(len(rel_edges))]
cur_ts = next_edge[3]
cur_node = next_edge[2]
body_ents_tss.append(next_edge[0])
body_ents_tss.append(cur_ts)
body_ents_tss.append(cur_node)
for cur_rel in body_rels[1:]:
next_edges = self.edges[cur_rel]
mask = (next_edges[:, 0] == cur_node) * (next_edges[:, 3] >= cur_ts)
filtered_edges = next_edges[mask]
if len(filtered_edges):
next_edge = filtered_edges[np.random.choice(len(filtered_edges))]
cur_ts = next_edge[3]
cur_node = next_edge[2]
body_ents_tss.append(cur_ts)
body_ents_tss.append(cur_node)
else:
sample_successful = False
break
if sample_successful and var_constraints:
# Check variable constraints
body_var_constraints = self.define_var_constraints(body_ents_tss[::2])
if body_var_constraints != var_constraints:
sample_successful = False
return sample_successful, body_ents_tss
def sample_acyclic_body(self, body_rels, constraint_tail):
"""
Sample an acyclic walk according to the rule body.
"""
sample_successful = True
body_ents_tss = []
cur_rel = body_rels[0]
rel_edges = self.edges[cur_rel]
mask = rel_edges[:,2] == constraint_tail
rel_edges = rel_edges[mask]
if len(rel_edges):
next_edge = rel_edges[np.random.choice(len(rel_edges))]
cur_ts = next_edge[3]
cur_node = next_edge[2]
body_ents_tss.append(next_edge[0])
body_ents_tss.append(cur_ts)
body_ents_tss.append(cur_node)
else:
sample_successful = False
return sample_successful, body_ents_tss
def calculate_rule_support(self, unique_bodies, head_rel):
rule_support = 0
head_rel_edges = self.edges[head_rel]
before_body = [-1, -1, -1]
before_mask = np.array([-1, -1, -1])
unique_bodies.sort(key=lambda x: x[::2] + [x[-2]])
for body in unique_bodies:
mask = (
(head_rel_edges[:, 0] == body[0])
* (head_rel_edges[:, 2] == body[-1])
* (head_rel_edges[:, 3] > body[-2])
)
if before_body == [-1, -1, -1] and True in mask:
rule_support += 1
before_body = body
before_mask = mask
continue
#print(operator.ne(mask.tolist(), before_mask.tolist()))
if before_body[::2] == body[::2] and operator.ne(mask.tolist(), before_mask.tolist()) and True in mask:
#print('2 fired')
rule_support += 1
before_body = body
before_mask = mask
continue
if before_body[::2] != body[::2] and True in mask:
rule_support += 1
before_body = body
before_mask = mask
continue
before_body = body
before_mask = mask
return rule_support
def calculate_acyclic_rule_support(self, unique_bodies, head_rel, head_constraint):
rule_support = 0
head_rel_edges = self.edges[head_rel]
before_body = [-1, -1, -1]
before_mask = np.array([-1, -1, -1])
unique_bodies.sort(key=lambda x: [x[0], x[-1], x[-2]])
#print(unique_bodies)
for body in unique_bodies:
mask = (
(head_rel_edges[:, 0] == body[0])
* (head_rel_edges[:, 3] > body[-2])
* (head_rel_edges[:, 2]== head_constraint)
)
if True in mask:
rule_support += 1
if before_body == [-1, -1, -1] and True in mask:
rule_support += 1
before_body = body
before_mask = mask
continue
#print(operator.ne(mask.tolist(), before_mask.tolist()))
if before_body[::2] == body[::2] and operator.ne(mask.tolist(), before_mask.tolist()) and True in mask:
#print('2 fired')
rule_support += 1
before_body = body
before_mask = mask
continue
if before_body[::2] != body[::2] and True in mask:
rule_support += 1
before_body = body
before_mask = mask
continue
before_body = body
before_mask = mask
return rule_support
def update_rules_dict(self, rule):
try:
self.rules_dict[rule["head_rel"]].append(rule)
except KeyError:
self.rules_dict[rule["head_rel"]] = [rule]
def sort_rules_dict(self):
for rel in self.rules_dict:
self.rules_dict[rel] = sorted(
self.rules_dict[rel], key=lambda x: x["conf"], reverse=True
)
def save_rules(self, dt, rule_lengths, num_walks, transition_distr, seed):
rules_dict = {int(k): v for k, v in self.rules_dict.items()}
filename = "{0}_r{1}_n{2}_{3}_s{4}_rules.json".format(
dt, rule_lengths, num_walks, transition_distr, seed
)
filename = filename.replace(" ", "")
with open(self.output_dir + filename, "w", encoding="utf-8") as fout:
json.dump(rules_dict, fout)
def save_rules_verbalized(
self, dt, rule_lengths, num_walks, transition_distr, seed
):
rules_str = ""
for rel in self.rules_dict:
for rule in self.rules_dict[rel]:
rules_str += verbalize_rule(rule, self.id2relation) + "\n"
filename = "{0}_r{1}_n{2}_{3}_s{4}_rules.txt".format(
dt, rule_lengths, num_walks, transition_distr, seed
)
filename = filename.replace(" ", "")
with open(self.output_dir + filename, "w", encoding="utf-8") as fout:
fout.write(rules_str)
def verbalize_rule(rule, id2relation):
if rule["var_constraints"]:
var_constraints = rule["var_constraints"]
constraints = [x for sublist in var_constraints for x in sublist]
for i in range(len(rule["body_rels"]) + 1):
if i not in constraints:
var_constraints.append([i])
var_constraints = sorted(var_constraints)
else:
var_constraints = [[x] for x in range(len(rule["body_rels"]) + 1)]
rule_str = "{0:8.6f} {1:4} {2:4} {3}(X0,X{4},T{5}) <- "
obj_idx = [
idx
for idx in range(len(var_constraints))
if len(rule["body_rels"]) in var_constraints[idx]
][0]
rule_str = rule_str.format(
rule["conf"],
rule["rule_supp"],
rule["body_supp"],
id2relation[rule["head_rel"]],
obj_idx,
len(rule["body_rels"]),
)
for i in range(len(rule["body_rels"])):
sub_idx = [
idx for idx in range(len(var_constraints)) if i in var_constraints[idx]
][0]
obj_idx = [
idx for idx in range(len(var_constraints)) if i + 1 in var_constraints[idx]
][0]
rule_str += "{0}(X{1},X{2},T{3}), ".format(
id2relation[rule["body_rels"][i]], sub_idx, obj_idx, i
)
return rule_str[:-2]
def rules_statistics(rules_dict):
print(
"Number of relations with rules: ", len(rules_dict)
) # Including inverse relations
print("Total number of rules: ", sum([len(v) for k, v in rules_dict.items()]))
lengths = []
for rel in rules_dict:
lengths += [len(x["body_rels"]) for x in rules_dict[rel]]
rule_lengths = [(k, v) for k, v in Counter(lengths).items()]
print("Number of rules by length: ", sorted(rule_lengths))