-
Notifications
You must be signed in to change notification settings - Fork 2
/
explain_utils.py
1854 lines (1747 loc) · 90.3 KB
/
explain_utils.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from enum import unique
import os
import multiprocessing
import subprocess
from copy import copy, deepcopy
import itertools
import pickle
import json
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestNeighbors
from scipy.sparse import vstack
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.model_selection import GridSearchCV
from sklearn.feature_extraction import DictVectorizer
import tqdm
from gingerit.gingerit import GingerIt
import torch
from explainable_kge.models import model_utils
from explainable_kge.logger.terminal_utils import logout
from explainable_kge.logger.viz_utils import figs2pdf
import pdb
def get_typed_knn(ent_embeddings, e2i=None, k=10):
"""
Provides k nearest neighbors of entities in embedding space
:param ent_embeddings:
"""
knn = {}
num_cpu = multiprocessing.cpu_count()
if e2i is not None:
ent_types = list(set([e[-1] for e in e2i.keys()]))
else:
ent_types = [None]
for ent_type in ent_types:
if ent_type is not None:
same_type_ents = [i for e, i in e2i.items() if e[-1] == ent_type]
else:
same_type_ents = list(e2i.values())
same_type_embeddings = ent_embeddings[same_type_ents]
type_k = min(k, len(same_type_ents))
nbrs = NearestNeighbors(n_neighbors=type_k, n_jobs=num_cpu, metric="euclidean").fit(same_type_embeddings)
_, knn_indices = nbrs.kneighbors(same_type_embeddings)
for row_id in range(knn_indices.shape[0]):
row = knn_indices[row_id]
knn[same_type_ents[row[0]]] = [same_type_ents[row[i]] for i in range(row.shape[0])]
logout("Typed KNN learning finished.","s")
return knn
def get_knn(embeddings):
num_cpu = multiprocessing.cpu_count()
nbrs = NearestNeighbors(n_neighbors=embeddings.shape[0], n_jobs=num_cpu, metric="euclidean").fit(embeddings)
return nbrs.kneighbors(embeddings)
def get_batch_from_generator(triples_iter, batch_size):
batch_heads = []
batch_rels = []
batch_tails = []
for i in range(batch_size):
try:
triple = next(triples_iter)
except StopIteration:
break
batch_heads.append(triple[0])
batch_rels.append(triple[1])
batch_tails.append(triple[2])
batch_heads = torch.tensor(batch_heads, dtype=torch.long)
batch_rels = torch.tensor(batch_rels, dtype=torch.long)
batch_tails = torch.tensor(batch_tails, dtype=torch.long)
return (batch_heads, batch_rels, batch_tails), len(batch_heads)
def get_p_triples(batch_head, batch_rel, batch_tail, i2e, i2r, scores, thresholds):
batch_head = batch_head.cpu().detach().numpy()
batch_rel = batch_rel.cpu().detach().numpy()
batch_tail = batch_tail.cpu().detach().numpy()
positives = []
for i in range(len(scores)):
if scores[i] > thresholds[batch_rel[i]]:
h = i2e[batch_head[i]]
r = i2r[batch_rel[i]]
t = i2e[batch_tail[i]]
positives.append([h,r,t])
return positives
def ghat_triple_generator(nbrs, dataset, max_nbrs):
num_head_nbrs = list(max_nbrs[0])
num_tail_nbrs = list(max_nbrs[1])
for batch in dataset:
h, r, t, _ = batch[0,:]
for ghat_triple in itertools.product(nbrs[h][:num_head_nbrs[r]], [r], nbrs[t][:num_tail_nbrs[r]]):
yield [ghat_triple[0], ghat_triple[1], ghat_triple[2]]
def generate_ghat(args, knn, dataset, model, thresholds, device, max_neighbors, ghat_path=None):
"""
Generates graph of positive triples for SFE input
:param args: experiment config
:param knn: nearest neighbors dict
:param dataset: dataset of triples to classify
:param model: pytorch nn.Module embedding object
:param thresholds: dict of relation thresholds {"rel": threshold}
:param device: cuda device
:param ghat_path: optional output path
:param max_neighbors: optional max number of neighbors to use for g_hat
:return: g_hat []
"""
g_hat = []
gen = ghat_triple_generator(knn, dataset, max_neighbors)
model.eval()
with torch.no_grad():
while True:
(bh, br, bt), bs = get_batch_from_generator(gen, 1000)
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), bt].cpu().detach().numpy()
else:
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device))
g_hat += get_p_triples(bh, br, bt, dataset.i2e, dataset.i2r, scores, thresholds)
if bs < 1000:
break
if ghat_path is not None:
pd.DataFrame(g_hat).to_csv(ghat_path, sep="\t", index=False, header=False)
logout("Generated G_hat. Size is " + str(len(g_hat)), "s")
return np.asarray(g_hat, dtype=str)
def process_ghat(ghat, e2i, i2e, r2i, i2r, num_gt_triples):
# combine all triples from ghat and gt
str_gt_triples = []
for row_id in range(num_gt_triples.shape[0]):
hi, ri, ti = num_gt_triples[row_id,:]
str_gt_triples.append([i2e[hi],i2r[ri],i2e[ti]])
str_gt_triples = np.asarray(str_gt_triples)
all_triples = np.unique(np.append(ghat, str_gt_triples, axis=0), axis=0)
# all_triples = ghat
# convert ghat into usable lookup table
valid_heads_rt = {}
valid_heads_r = {}
valid_tails_rh = {}
valid_tails_r = {}
for i in range(all_triples.shape[0]):
h, r, t = all_triples[i,:]
h_i = e2i[h]
r_i = r2i[r]
t_i = e2i[t]
if (r_i,t_i) not in valid_heads_rt:
valid_heads_rt[(r_i,t_i)] = [h_i]
elif h_i not in valid_heads_rt[(r_i,t_i)]:
valid_heads_rt[(r_i,t_i)].append(h_i)
if r_i not in valid_heads_r:
valid_heads_r[r_i] = [h_i]
elif h_i not in valid_heads_r[r_i]:
valid_heads_r[r_i].append(h_i)
if (r_i,h_i) not in valid_tails_rh:
valid_tails_rh[(r_i,h_i)] = [t_i]
elif t_i not in valid_tails_rh[(r_i,h_i)]:
valid_tails_rh[(r_i,h_i)].append(t_i)
if r_i not in valid_tails_r:
valid_tails_r[r_i] = [t_i]
elif t_i not in valid_tails_r[r_i]:
valid_tails_r[r_i].append(t_i)
# also load corrupt domains
rel_heads = {}
rel_tails = {}
for row_id in range(all_triples.shape[0]):
h, r, t = all_triples[row_id, :]
if r not in rel_heads:
rel_heads[r] = []
if r not in rel_tails:
rel_tails[r] = []
if h not in rel_heads[r]:
rel_heads[r].append(h)
if t not in rel_tails[r]:
rel_tails[r].append(t)
# assign the full domains
h_dom = {}
t_dom = {}
for r in rel_heads.keys():
for t in rel_tails[r]:
h_dom[(r,t)] = deepcopy(rel_heads[r])
for h in rel_heads[r]:
t_dom[(r,h)] = deepcopy(rel_tails[r])
# remove all head/tails from relation domain in triples
for row_id in range(all_triples.shape[0]):
h, r, t = all_triples[row_id,:]
if t in t_dom[(r,h)]:
del t_dom[(r,h)][t_dom[(r,h)].index(t)]
if h in h_dom[(r,t)]:
del h_dom[(r,t)][h_dom[(r,t)].index(h)]
return valid_heads_rt, valid_heads_r, valid_tails_rh, valid_tails_r, h_dom, t_dom
def load_datasets_to_dataframes(args):
"""
Loads all splits for a dataset into pandas DataFrames given the experiment config
:param args: experiment config
:return: tuple of pandas DataFrames for each split
"""
# dev set
dev_args = copy(args)
dev_args["continual"]["session"] = 0
dev_args["dataset"]["set_name"] = "0_valid2id"
de_p_d = model_utils.load_dataset(dev_args)
p_triples = copy(de_p_d.triples)
p_triples = np.append(p_triples, np.ones(shape=(p_triples.shape[0],1), dtype=np.int), axis=1)
dev_args["dataset"]["set_name"] = "0_valid2id_neg"
de_n_d = model_utils.load_dataset(dev_args)
n_triples = copy(de_n_d.triples)
n_triples = np.append(n_triples, -np.ones(shape=(n_triples.shape[0],1), dtype=np.int), axis=1)
de_df = pd.DataFrame(np.concatenate((p_triples, n_triples), axis=0))
# test set
test_args = copy(args)
test_args["continual"]["session"] = 0
test_args["dataset"]["set_name"] = "0_test2id"
te_p_d = model_utils.load_dataset(test_args)
p_triples = copy(te_p_d.triples)
p_triples = np.append(p_triples, np.ones(shape=(p_triples.shape[0],1), dtype=np.int), axis=1)
test_args["dataset"]["set_name"] = "0_test2id_neg"
te_n_d = model_utils.load_dataset(test_args)
n_triples = copy(te_n_d.triples)
n_triples = np.append(n_triples, -np.ones(shape=(n_triples.shape[0],1), dtype=np.int), axis=1)
te_df = pd.DataFrame(np.concatenate((p_triples, n_triples), axis=0))
# train set
train_args = copy(args)
train_args["dataset"]["set_name"] = "0_train2id"
train_args["continual"]["session"] = 0
train_args["dataset"]["neg_ratio"] = 1
tr_dataset = model_utils.load_dataset(train_args)
tr_dataset.load_bernouli_sampling_stats()
tr_dataset.load_corrupt_domains()
tr_dataset.load_current_ents_rels()
tr_dataset.load_known_ent_set()
tr_dataset.load_known_rel_set()
tr_dataset.model_name = None # makes __getitem__ only retrieve triples instead of triple pairs
tr_df = pd.DataFrame(np.concatenate([tr_dataset[i] for i in range(len(tr_dataset))], axis=0))
return tr_df, de_df, te_df
def create_split(dfs, splits_dirpath, split_name):
"""Creates a split directory that PRA algorithm can use for the respective dataset.
Arguments:
- dfs: a dict whose keys are fold names (e.g. "train", "test") and values are DataFrames with
head, tail, relation, and label columns.
- split_dirpath: path where the split should be created.
"""
if not os.path.exists(splits_dirpath):
os.makedirs(splits_dirpath)
this_split_path = splits_dirpath + '/' + split_name
if not os.path.exists(this_split_path):
os.makedirs(this_split_path)
# get relations
rels = set()
for _, df in dfs.items():
rels.update(df[1].unique())
# create relations_to_run.tsv file
with open(this_split_path + '/relations_to_run.tsv', 'w') as f:
for rel in rels:
f.write('{}\n'.format(rel))
# create each relation dir and its files
for rel in rels:
for fold_name, df in dfs.items():
relpath = '{}/{}/'.format(this_split_path, rel)
if not os.path.exists(relpath):
os.makedirs(relpath)
filtered = df.loc[df[1] == rel]
filtered.to_csv('{}/{}.tsv'.format(relpath, fold_name),
columns=[0, 2, 3], index=False, header=False, sep='\t')
def run_sfe(args, model, device, rel_thresholds, i2e, i2r,
split_fp, split_name, ghat_path, main_fp):
"""
"""
train_df, dev_df, test_df = load_datasets_to_dataframes(args)
with torch.no_grad():
for df in [train_df, dev_df, test_df]:
bh = torch.tensor(df[0], dtype=torch.long)
br = torch.tensor(df[1], dtype=torch.long)
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), df[2]].cpu().detach().numpy()
else:
bt = torch.tensor(df[2], dtype=torch.long)
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device))
for i in range(len(scores)):
if scores[i] > rel_thresholds[df.loc[i,1]]:
df.loc[i,3] = 1
else:
df.loc[i,3] = -1
df.loc[i,0] = i2e[df.loc[i,0]]
df.loc[i,1] = i2r[df.loc[i,1]]
df.loc[i,2] = i2e[df.loc[i,2]]
create_split({"train":train_df, "valid": dev_df, "test": test_df}, split_fp, split_name)
rel_meta_str = ""
if args["dataset"]["reverse"]:
assert len(i2r) % 2 == 0
rev_offset = int(len(i2r) / 2)
rev_rel_map = pd.DataFrame()
for rel_idx in range(rev_offset):
rel = i2r[rel_idx]
rev_rel = i2r[rel_idx + rev_offset]
rev_rel_map = rev_rel_map.append({0: rel, 1: rev_rel}, ignore_index=True)
rel_meta_fp = '{}/{}.tsv'.format(main_fp, "inverses")
rev_rel_map.to_csv(rel_meta_fp,
columns=[0, 1], index=False, header=False, sep='\t')
rel_meta_str = '"relation metadata": "{}",'.format(rel_meta_fp)
spec = """
{{
"graph": {{
"name": "{}",
"relation sets": [
{{
"is kb": false,
"relation file": "{}"
}}
]
}},
{}
"split": "{}",
"operation": {{
"type": "create matrices",
"features": {{
"type": "subgraphs",
"path finder": {{
"type": "BfsPathFinder",
"number of steps": 2
}},
"feature extractors": [
{}
],
"feature size": -1
}},
"data": "{}"
}},
"output": {{ "output matrices": true }}
}}
""".format("ghat", ghat_path, rel_meta_str, split_name, '"PraFeatureExtractor"', "onefold")
if not os.path.exists('{}/experiment_specs'.format(main_fp)):
os.makedirs('{}/experiment_specs'.format(main_fp))
spec_fpath = '{}/experiment_specs/{}.json'.format(main_fp, split_name)
with open(spec_fpath, 'w') as f:
f.write(spec)
bash_command = '/media/adaruna3/melodic/explainable-kge/explainable_kge/run_pra.sh {} {}'.format(main_fp, split_name)
n_runs = len(i2r) * 3
for r in tqdm.tqdm(range(n_runs)):
print("Running #{}: {}".format(r, bash_command))
process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if str(error) != "None":
logout(error, "f")
logout(output, "d")
exit()
logout("SFE finished", "s")
def parse_feature_matrix(filepath):
"""Returns four objects: three lists (of heads, tails and labels) and a sparse matrix (of
features) for the input (a path to a feature matrix file).
"""
heads = []
tails = []
labels = []
feat_dicts = []
with open(filepath, 'r') as f:
for line in f:
ent_pair, label, features = line.replace('\n', '').split('\t')
head, tail = ent_pair.split(',')
d = {}
if features:
for feat in features.split(' -#- '):
feat_name, value = feat.split(',')
d[feat_name] = float(value)
heads.append(head)
tails.append(tail)
labels.append(int(label))
feat_dicts.append(d)
return np.array(heads), np.array(tails), np.array(labels), feat_dicts
def get_reasons(row, n=10):
# Remove zero elements
reasons = row[row != 0]
# Select the top n_examples elements
top_reasons_abs = reasons.abs().nlargest(n=n, keep='first')
# Create a pandas series with these
output = pd.Series()
counter = 1
for reason, _ in top_reasons_abs.iteritems():
output['reason' + str(counter)] = reason
output['relevance' + str(counter)] = reasons[reason]
counter = counter + 1
if counter == n:
break
for i in range(counter, n):
output['reason' + str(i)] = "n/a"
output['relevance' + str(i)] = "n/a"
return output, top_reasons_abs.index.to_numpy(dtype=str)
def get_logit_explain_paths(ex_fp, rel, example_num, feats, feat_names, coeff, head, tail, pred, label):
if not os.path.exists(ex_fp):
os.makedirs(ex_fp)
feats = feats.todense()
explanations = np.multiply(feats, coeff).reshape(1, -1)
example_df = pd.DataFrame(explanations, columns=feat_names)
final_reasons, paths = example_df.apply(get_reasons, axis=1)[0]
final_reasons['head'] = head
final_reasons['tail'] = tail
final_reasons['y_logit'] = pred
final_reasons['y_hat'] = label
final_reasons.to_csv(os.path.join(ex_fp, rel + "_ex" + str(example_num) + "_" + str(head) + '_' + str(tail) + '.tsv'), sep='\t')
return paths
def get_dt_explain_paths(ex_fp, rel, example_num, example, model, feat_names, head, tail, pred, label, plot_tree):
if not os.path.exists(ex_fp):
os.makedirs(ex_fp)
file_name = rel + "_ex" + str(example_num) + "_" + str(head) + '_' + str(tail)
if plot_tree:
# save whole tree
plt.axis("tight")
plot_tree(model, class_names=["False", "True"], feature_names=feat_names, node_ids=True, filled=True)
plt.savefig(os.path.join(ex_fp, file_name + ".pdf"), bbox_inches='tight', dpi=100)
# save decision path
explanation_df = pd.DataFrame(columns=["rule","head","tail","y_logit","y_hat"])
explanation_df = explanation_df.append({"head": head, "tail": tail, "y_logit": pred, "y_hat": label}, ignore_index=True)
decision_path_nodes = model.decision_path(example).indices
leaf = model.apply(example)
paths = []
for node in decision_path_nodes:
if node == leaf: continue
feat_idx = model.tree_.feature[node]
path = feat_names[feat_idx].replace("-",",").replace("_","Reverse ")[1:-1]
if example[0,feat_idx]:
explanation_df = explanation_df.append({"rule": "Path {} exists".format(path)}, ignore_index=True)
paths.append(feat_names[feat_idx])
else:
explanation_df = explanation_df.append({"rule": "Path {} missing".format(path)}, ignore_index=True)
explanation_df.to_csv(os.path.join(ex_fp, file_name + '.tsv'), sep='\t')
return np.asarray(paths, dtype=str)
def fr_hop(args, r_i, h_i, ghat, next_r, r2i, dflag, model, device):
valid_heads_rh, valid_heads_r, valid_tails_rt, valid_tails_r, _, _ = ghat
# get tails that are compatible with next relation
t_i = valid_tails_rt[(r_i,h_i)]
if dflag == "fr":
if next_r[0] == "_":
t_i_valid = valid_tails_r[r2i[next_r[1:]]]
else:
t_i_valid = valid_heads_r[r2i[next_r]]
else:
if next_r[0] == "_":
t_i_valid = valid_heads_r[r2i[next_r[1:]]]
else:
t_i_valid = valid_tails_r[r2i[next_r]]
t_i = list(set(t_i).intersection(set(t_i_valid)))
assert len(t_i)
# given head and relation, return most likely tail
bh = torch.tensor(h_i, dtype=torch.long).repeat(len(t_i))
br = torch.tensor(r_i, dtype=torch.long).repeat(len(t_i))
bt = torch.tensor(t_i, dtype=torch.long)
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))[0,bt].cpu().detach().numpy()
else:
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device))
return t_i, scores
def bk_hop(args, r_i, t_i, ghat, next_r, r2i, dflag, model, device):
valid_heads_rh, valid_heads_r, valid_tails_rt, valid_tails_r, _, _ = ghat
h_i = valid_heads_rh[(r_i,t_i)]
if dflag == "fr":
if next_r[0] == "_":
h_i_valid = valid_tails_r[r2i[next_r[1:]]]
else:
h_i_valid = valid_heads_r[r2i[next_r]]
else:
if next_r[0] == "_":
h_i_valid = valid_heads_r[r2i[next_r[1:]]]
else:
h_i_valid = valid_tails_r[r2i[next_r]]
h_i = list(set(h_i).intersection(set(h_i_valid)))
assert len(h_i)
# given tail and relation, return most likely head
bh = torch.tensor(h_i, dtype=torch.long)
br = torch.tensor(r_i, dtype=torch.long).repeat(len(bh))
bt = torch.tensor(t_i, dtype=torch.long).repeat(len(bh))
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), bt].cpu().detach().numpy()
else:
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device))
return h_i, scores
def forward_path_search(args, path, head, ghat, e2i, i2e, r2i, model, device):
# get tails for current path step
hop_str = path[0]
if hop_str[0] == "_":
# fr 'reverse' hop
r = hop_str[1:]
t_i_s, scores = bk_hop(args, r2i[r], e2i[head], ghat, path[1], r2i, "fr", model, device)
else:
# fr hop
r = hop_str
t_i_s, scores = fr_hop(args, r2i[r], e2i[head], ghat, path[1], r2i, "fr", model, device)
# if path size is two, return the tail paths for head with scores
if len(path) == 2:
return [[[head,hop_str,i2e[t_i]]] for t_i in t_i_s], scores
# if path greater than two, recursively get rest of path and merge with current
gnd_paths_fr = []
gnd_scores = []
for t_i_idx in range(len(t_i_s)):
t_i = t_i_s[t_i_idx]
gnd_paths, scores2 = forward_path_search(args, path[1:], i2e[t_i], ghat, e2i, i2e, r2i, model, device)
for gnd_idx in range(len(gnd_paths)):
gnd_paths_fr.append(gnd_paths[gnd_idx].insert(0, [head,hop_str,i2e[t_i]]))
gnd_scores.append(scores[t_i_idx] + scores2[gnd_idx])
return gnd_paths_fr, gnd_scores
def backward_path_search(args, path, tail, ghat, e2i, i2e, r2i, model, device):
hop_str = path[-1]
if hop_str[0] == "_":
# bk 'reverse' hop
r = hop_str[1:]
h_i_s, scores = fr_hop(args, r2i[r], e2i[tail], ghat, path[-2], r2i, "bk", model, device)
else:
# bk hop
r = hop_str
h_i_s, scores = bk_hop(args, r2i[r], e2i[tail], ghat, path[-2], r2i, "bk", model, device)
# if path size is two, return the tail paths for head with scores
if len(path) == 2:
return [[[i2e[h_i],hop_str,tail]] for h_i in h_i_s], scores
# if path greater than two, recursively get rest of path and merge with current
gnd_paths_bk = []
gnd_scores = []
for h_i_idx in range(len(h_i_s)):
h_i = h_i_s[h_i_idx]
gnd_paths, scores2 = backward_path_search(args, path[:-1], i2e[h_i], ghat, e2i, i2e, r2i, model, device)
for gnd_idx in range(len(gnd_paths)):
gnd_paths_bk.append(gnd_paths[gnd_idx].append([i2e[h_i],hop_str,tail]))
gnd_scores.append(scores[h_i_idx] + scores2[gnd_idx])
return gnd_paths_bk, gnd_scores
def order_possible_paths(args, scores1, scores2):
score_tbl = {}
scores = []
if scores1.shape[0] and scores2.shape[0]:
for i in range(len(scores1)):
for j in range(len(scores2)):
score_tbl[len(scores)] = (i, j)
scores.append(scores1[i] + scores2[j])
if args["model"]["name"] == "tucker":
_, sort_idxs = torch.sort(torch.tensor(scores), descending=True)
sort_idxs = sort_idxs.cpu().numpy()
else:
sort_idxs = np.argsort(scores)
ids1 = []
ids2 = []
for idx in range(len(sort_idxs)):
id1, id2 = score_tbl[sort_idxs[idx]]
ids1.append(id1)
ids2.append(id2)
elif scores1.shape[0] and not scores2.shape[0]:
for i in range(len(scores1)):
score_tbl[len(scores)] = (i, None)
scores.append(scores1[i])
if args["model"]["name"] == "tucker":
_, sort_idxs = torch.sort(torch.tensor(scores), descending=True)
sort_idxs = sort_idxs.cpu().numpy()
else:
sort_idxs = np.argsort(scores)
ids1 = []
ids2 = []
for idx in range(len(sort_idxs)):
id1, id2 = score_tbl[sort_idxs[idx]]
ids1.append(id1)
ids2.append(id2)
elif not scores1.shape[0] and not scores2.shape[0]:
ids1 = [None]
ids2 = [None]
else:
pdb.set_trace()
return ids1, ids2
def get_connection_ends(h, fr_path, fr_idx, t, bk_path, bk_idx):
if fr_idx is None:
fr_h = h
else:
fr_h = fr_path[fr_idx][-1][-1]
if bk_idx is None:
bk_t = t
else:
bk_t = bk_path[bk_idx][0][0]
return fr_h, bk_t
def path_connection(args, fr_h_i, fr_r_str, bk_t_i, bk_r_str, ghat, r2i, i2e, model, device):
valid_heads_rh, valid_heads_r, valid_tails_rt, valid_tail_r, _, _ = ghat
if fr_r_str[0] != "_" and bk_r_str[0] != "_":
# neither hop is reversed
fr_r_i = r2i[fr_r_str]
fr_t_i = valid_tails_rt[(fr_r_i,fr_h_i)]
bk_r_i = r2i[bk_r_str]
bk_h_i = valid_heads_rh[(bk_r_i,bk_t_i)]
connections = list(set(fr_t_i).intersection(set(bk_h_i)))
if not len(connections): return False
if len(connections) == 1: return connections
bc = torch.tensor(connections, dtype=torch.long)
fr_bh = torch.tensor(fr_h_i, dtype=torch.long).repeat(len(connections))
fr_br = torch.tensor(fr_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
fr_scores = model.predict(fr_bh.contiguous().to(device),
fr_br.contiguous().to(device))[0,bc]
else:
fr_scores = model.predict(fr_bh.contiguous().to(device),
fr_br.contiguous().to(device),
bc.contiguous().to(device))
bk_bt = torch.tensor(bk_t_i, dtype=torch.long).repeat(len(connections))
bk_br = torch.tensor(bk_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
bk_scores = model.predict(bc.contiguous().to(device),
bk_br.contiguous().to(device))
bk_scores = bk_scores[torch.arange(0, len(bc), device=device, dtype=torch.long), bk_bt]
else:
bk_scores = model.predict(bc.contiguous().to(device),
bk_br.contiguous().to(device),
bk_bt.contiguous().to(device))
elif fr_r_str[0] == "_" and bk_r_str[0] != "_":
# only forward hop reversed
fr_r_i = r2i[fr_r_str[1:]]
fr_t_i = valid_heads_rh[(fr_r_i,fr_h_i)]
bk_r_i = r2i[bk_r_str]
bk_h_i = valid_heads_rh[(bk_r_i,bk_t_i)]
connections = list(set(fr_t_i).intersection(set(bk_h_i)))
if not len(connections): return False
if len(connections) == 1: return connections
bc = torch.tensor(connections, dtype=torch.long)
fr_bh = torch.tensor(fr_h_i, dtype=torch.long).repeat(len(connections))
fr_br = torch.tensor(fr_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
fr_scores = model.predict(bc.contiguous().to(device),
fr_br.contiguous().to(device))
fr_scores = fr_scores[torch.arange(0, len(bc), device=device, dtype=torch.long), fr_bh]
else:
fr_scores = model.predict(bc.contiguous().to(device),
fr_br.contiguous().to(device),
fr_bh.contiguous().to(device))
bk_bt = torch.tensor(bk_t_i, dtype=torch.long).repeat(len(connections))
bk_br = torch.tensor(bk_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
bk_scores = model.predict(bc.contiguous().to(device),
bk_br.contiguous().to(device))
bk_scores = bk_scores[torch.arange(0, len(bc), device=device, dtype=torch.long), bk_bt]
else:
bk_scores = model.predict(bc.contiguous().to(device),
bk_br.contiguous().to(device),
bk_bt.contiguous().to(device))
elif fr_r_str[0] != "_" and bk_r_str[0] == "_":
# only backward hop reversed
fr_r_i = r2i[fr_r_str]
fr_t_i = valid_tails_rt[(fr_r_i,fr_h_i)]
bk_r_i = r2i[bk_r_str[1:]]
bk_h_i = valid_tails_rt[(bk_r_i,bk_t_i)]
connections = list(set(fr_t_i).intersection(set(bk_h_i)))
if not len(connections): return False
if len(connections) == 1: return connections
bc = torch.tensor(connections, dtype=torch.long)
fr_bh = torch.tensor(fr_h_i, dtype=torch.long).repeat(len(connections))
fr_br = torch.tensor(fr_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
fr_scores = model.predict(fr_bh.contiguous().to(device),
fr_br.contiguous().to(device))[0,bc]
else:
fr_scores = model.predict(fr_bh.contiguous().to(device),
fr_br.contiguous().to(device),
bc.contiguous().to(device))
bk_bt = torch.tensor(bk_t_i, dtype=torch.long).repeat(len(connections))
bk_br = torch.tensor(bk_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
bk_scores = model.predict(bk_bt.contiguous().to(device),
bk_br.contiguous().to(device))[0,bc]
else:
bk_scores = model.predict(bk_bt.contiguous().to(device),
bk_br.contiguous().to(device),
bc.contiguous().to(device))
else:
# both hops reversed
fr_r_i = r2i[fr_r_str[1:]]
fr_t_i = valid_heads_rh[(fr_r_i,fr_h_i)]
bk_r_i = r2i[bk_r_str[1:]]
bk_h_i = valid_tails_rt[(bk_r_i,bk_t_i)]
connections = list(set(fr_t_i).intersection(set(bk_h_i)))
if not len(connections): return False
if len(connections) == 1: return connections
bc = torch.tensor(connections, dtype=torch.long)
fr_bh = torch.tensor(fr_h_i, dtype=torch.long).repeat(len(connections))
fr_br = torch.tensor(fr_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
fr_scores = model.predict(bc.contiguous().to(device),
fr_br.contiguous().to(device))
fr_scores = fr_scores[torch.arange(0, len(bc), device=device, dtype=torch.long), fr_bh]
else:
fr_scores = model.predict(bc.contiguous().to(device),
fr_br.contiguous().to(device),
fr_bh.contiguous().to(device))
bk_bt = torch.tensor(bk_t_i, dtype=torch.long).repeat(len(connections))
bk_br = torch.tensor(bk_r_i, dtype=torch.long).repeat(len(connections))
if args["model"]["name"] == "tucker":
bk_scores = model.predict(bk_bt.contiguous().to(device),
bk_br.contiguous().to(device))[0,bc]
else:
bk_scores = model.predict(bk_bt.contiguous().to(device),
bk_br.contiguous().to(device),
bc.contiguous().to(device))
scores = fr_scores + bk_scores
if args["model"]["name"] == "tucker":
_, sort_idxs = torch.sort(scores, descending=True)
sort_idxs = sort_idxs.cpu().numpy()
else:
sort_idxs = np.argsort(scores)
return np.asarray(connections)[sort_idxs].tolist()
def get_path_corrupt_parts(short_path):
if len(short_path) > 2:
num_corrupt_parts = np.random.randint(1,3)
else:
num_corrupt_parts = 1
possible_corrupt_parts = [i for i in range(len(short_path) + 1)]
corrupt_parts = []
while len(corrupt_parts) < num_corrupt_parts:
if len(corrupt_parts) == 0: # ensure head or tail of predicted triple corrupted
corrupt_parts.append(np.random.choice([0,len(short_path)]))
if corrupt_parts[-1] == 0:
possible_corrupt_parts.pop(len(short_path))
else:
possible_corrupt_parts.pop(0)
else:
corrupt_parts.append(np.random.choice(possible_corrupt_parts))
possible_corrupt_parts.pop(possible_corrupt_parts.index(corrupt_parts[-1]))
if corrupt_parts[-1]+1 in possible_corrupt_parts:
possible_corrupt_parts.pop(possible_corrupt_parts.index(corrupt_parts[-1]+1))
if corrupt_parts[-1]-1 in possible_corrupt_parts:
possible_corrupt_parts.pop(possible_corrupt_parts.index(corrupt_parts[-1]-1))
return corrupt_parts
def get_bad_ents(args, correct_part, ghat, e2i, i2e, r2i, head_flag, corrupting_ends, end_head, end_rel, end_tail, model, device, num_corrections=3):
valid_heads_rt, _, valid_tails_rh, _, h_dom, t_dom = ghat
h, r, t = correct_part
if head_flag:
# corrupt head with least likely, invalid, same type heads
if r[0] == "_":
incorrect_ents = t_dom[(r[1:],t)]
else:
incorrect_ents = h_dom[(r,t)]
if corrupting_ends:
# account for corrupting ends
if end_rel[0] == "_":
if (end_rel[1:],end_tail) in t_dom:
incorrect_ents = list(set(incorrect_ents).union(set(t_dom[(end_rel[1:],end_tail)])))
else:
if (end_rel,end_tail) in h_dom:
incorrect_ents = list(set(incorrect_ents).union(set(h_dom[(end_rel,end_tail)])))
if len(incorrect_ents):
# rank according to likelihood of satisfying relationship
bh = torch.tensor([e2i[ent] for ent in incorrect_ents], dtype=torch.long)
br = torch.tensor(r2i[r.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[t], dtype=torch.long).repeat(len(bh))
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
if corrupting_ends:
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[end_tail], dtype=torch.long).repeat(len(bh))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores_ = scores_[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
scores += scores_
_, sort_idxs = torch.sort(scores, descending=True)
sort_idxs = sort_idxs.cpu().detach().numpy()
else:
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
if corrupting_ends:
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[end_tail], dtype=torch.long).repeat(len(bh))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
scores += scores_
sort_idxs = np.argsort(scores)
all_bad_heads = np.asarray(incorrect_ents)[sort_idxs].tolist()
bad_heads = get_non_repeats_end(all_bad_heads, num_corrections)
else:
bad_heads = []
if len(bad_heads) < 3:
# add least likely, invalid corrupt heads if needed
possible_bad_heads = np.arange(len(e2i))
if r[0] == "_":
if (r2i[r[1:]],e2i[t]) in valid_tails_rh:
valid_heads = valid_tails_rh[(r2i[r[1:]],e2i[t])]
possible_bad_heads[np.isin(possible_bad_heads, valid_heads, invert=True)]
else:
if (r2i[r],e2i[t]) in valid_heads_rt:
valid_heads = valid_heads_rt[(r2i[r],e2i[t])]
possible_bad_heads[np.isin(possible_bad_heads, valid_heads, invert=True)]
if corrupting_ends:
if end_rel[0] == "_":
if (r2i[end_rel[1:]],e2i[end_tail]) in valid_tails_rh:
valid_heads = valid_tails_rh[(r2i[end_rel[1:]],e2i[end_tail])]
possible_bad_heads[np.isin(possible_bad_heads, valid_heads, invert=True)]
else:
if (r2i[end_rel],e2i[end_tail]) in valid_heads_rt:
valid_heads = valid_heads_rt[(r2i[end_rel],e2i[end_tail])]
possible_bad_heads[np.isin(possible_bad_heads, valid_heads, invert=True)]
# rank according to likelihood of satisfying relationship
bh = torch.tensor(possible_bad_heads, dtype=torch.long)
br = torch.tensor(r2i[r.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[t], dtype=torch.long).repeat(len(bh))
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
if corrupting_ends:
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[end_tail], dtype=torch.long).repeat(len(bh))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores_ = scores_[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
scores += scores_
_, sort_idxs = torch.sort(scores, descending=True)
sort_idxs = sort_idxs.cpu().detach().numpy()
else:
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
if corrupting_ends:
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[end_tail], dtype=torch.long).repeat(len(bh))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
scores += scores_
sort_idxs = np.argsort(scores)
all_bad_heads = [i2e[e_id] for e_id in np.asarray(possible_bad_heads)[sort_idxs].tolist()] + bad_heads
bad_heads = get_non_repeats_end(all_bad_heads, num_corrections)
return bad_heads
else:
# corrupt tail with least likely, invalid, same type tails
if r[0] == "_":
incorrect_ents = h_dom[(r[1:],h)]
else:
incorrect_ents = t_dom[(r,h)]
if corrupting_ends:
# account for corrupting ends
if end_rel[0] == "_":
if (end_rel[1:],end_head) in h_dom:
incorrect_ents = list(set(incorrect_ents).union(set(h_dom[(end_rel[1:],end_head)])))
else:
if (end_rel,end_head) in t_dom:
incorrect_ents = list(set(incorrect_ents).union(set(t_dom[(end_rel,end_head)])))
# rank according to likelihood of satisfying relationship
if len(incorrect_ents):
bt = torch.tensor([e2i[ent] for ent in incorrect_ents], dtype=torch.long)
br = torch.tensor(r2i[r.replace("_","")], dtype=torch.long).repeat(len(bt))
bh = torch.tensor(e2i[h], dtype=torch.long).repeat(len(bt))
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
if corrupting_ends: # corrupting last tail, account for that
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bt))
bh = torch.tensor(e2i[end_head], dtype=torch.long).repeat(len(bt))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores_ = scores_[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
scores += scores_
_, sort_idxs = torch.sort(scores, descending=True)
sort_idxs = sort_idxs.cpu().detach().numpy()
else:
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
if corrupting_ends: # corrupting last tail, account for that
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bt))
bh = torch.tensor(e2i[end_head], dtype=torch.long).repeat(len(bt))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
scores += scores_
sort_idxs = np.argsort(scores)
all_bad_tails = np.asarray(incorrect_ents)[sort_idxs].tolist()
bad_tails = get_non_repeats_end(all_bad_tails, num_corrections)
else:
bad_tails = []
if len(bad_tails) < 3:
# add least likely, invalid corrupt tails if needed
possible_bad_tails = np.arange(len(e2i))
if r[0] == "_":
if (r2i[r[1:]],e2i[h]) in valid_heads_rt:
valid_tails = valid_heads_rt[(r2i[r[1:]],e2i[h])]
possible_bad_tails[np.isin(possible_bad_tails, valid_tails, invert=True)]
else:
if (r2i[r],e2i[h]) in valid_tails_rh:
valid_tails = valid_tails_rh[(r2i[r],e2i[h])]
possible_bad_tails[np.isin(possible_bad_tails, valid_tails, invert=True)]
if corrupting_ends:
if end_rel[0] == "_":
if (r2i[end_rel[1:]],e2i[end_head]) in valid_heads_rt:
valid_tails = valid_heads_rt[(r2i[end_rel[1:]],e2i[end_head])]
possible_bad_tails[np.isin(possible_bad_tails, valid_tails, invert=True)]
else:
if (r2i[end_rel],e2i[end_head]) in valid_tails_rh:
valid_tails = valid_tails_rh[(r2i[end_rel],e2i[end_head])]
possible_bad_tails[np.isin(possible_bad_tails, valid_tails, invert=True)]
# rank according to likelihood of satisfying relationship
bt = torch.tensor(possible_bad_tails, dtype=torch.long)
br = torch.tensor(r2i[r.replace("_","")], dtype=torch.long).repeat(len(bt))
bh = torch.tensor(e2i[h], dtype=torch.long).repeat(len(bt))
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
if corrupting_ends: # corrupting last tail, account for that
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bt))
bh = torch.tensor(e2i[end_head], dtype=torch.long).repeat(len(bt))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores_ = scores_[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
scores += scores_
_, sort_idxs = torch.sort(scores, descending=True)
sort_idxs = sort_idxs.cpu().detach().numpy()
else:
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
if corrupting_ends: # corrupting last tail, account for that
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bt))
bh = torch.tensor(e2i[end_head], dtype=torch.long).repeat(len(bt))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device), bt.contiguous().to(device)).cpu().detach().numpy()
scores += scores_
sort_idxs = np.argsort(scores)
all_bad_tails = [i2e[e_id] for e_id in np.asarray(possible_bad_tails)[sort_idxs].tolist()] + bad_tails
bad_tails = get_non_repeats_end(all_bad_tails, num_corrections)
return bad_tails
def get_other_ents(args, correct_part, ghat, e2i, i2e, r2i, head_flag, corrupting_ends, end_head, end_rel, end_tail, model, device, num_corrections=3):
valid_heads_rt, valid_heads_r, valid_tails_rh, valid_tails_r, _, _ = ghat
h, r, t = correct_part
if head_flag:
filter_heads = [h, end_head] if corrupting_ends else [h]
# corrupt head with most likely, valid, same type heads
if r[0] == "_":
incorrect_ents = valid_tails_rh[(r2i[r[1:]],e2i[t])]
else:
incorrect_ents = valid_heads_rt[(r2i[r],e2i[t])]
if corrupting_ends:
# account for corrupting ends
if end_rel[0] == "_":
if (r2i[end_rel[1:]],e2i[end_tail]) in valid_tails_rh:
incorrect_ents = list(set(incorrect_ents).union(set(valid_tails_rh[(r2i[end_rel[1:]],e2i[end_tail])])))
else:
if (r2i[end_rel],e2i[end_tail]) in valid_heads_rt:
incorrect_ents = list(set(incorrect_ents).union(set(valid_heads_rt[(r2i[end_rel],e2i[end_tail])])))
if len(incorrect_ents):
# rank according to likelihood of satisfying relationship
bh = torch.tensor(incorrect_ents, dtype=torch.long)
br = torch.tensor(r2i[r.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[t], dtype=torch.long).repeat(len(bh))
if args["model"]["name"] == "tucker":
scores = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores = scores[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
if corrupting_ends:
br = torch.tensor(r2i[end_rel.replace("_","")], dtype=torch.long).repeat(len(bh))
bt = torch.tensor(e2i[end_tail], dtype=torch.long).repeat(len(bh))
scores_ = model.predict(bh.contiguous().to(device), br.contiguous().to(device))
scores_ = scores_[torch.arange(0, len(bh), device=device, dtype=torch.long), bt]
scores += scores_
_, sort_idxs = torch.sort(scores, descending=True)
sort_idxs = sort_idxs.cpu().detach().numpy()