-
Notifications
You must be signed in to change notification settings - Fork 2
/
Evaluating_HITS-semrec.py
executable file
·544 lines (397 loc) · 13.3 KB
/
Evaluating_HITS-semrec.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
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import click as ck
import numpy as np
import pandas as pd
import logging
import math
import os
from collections import deque
import pickle as pkl
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.manifold import TSNE
from sklearn.metrics import roc_curve, auc, matthews_corrcoef
import matplotlib.pyplot as plt
from scipy.stats import rankdata
logging.basicConfig(level=logging.INFO)
import operator
from collections import Counter
class ELModel(nn.Module):
def __init__(self, nb_classes, nb_relations, embedding_size, batch_size, margin, reg_norm):
super(ELModel, self).__init__()
self.nb_classes = nb_classes
self.nb_relations = nb_relations
self.embedding_size = embedding_size
self.batch_size = batch_size
self.margin = margin
self.reg_norm = reg_norm
width = 3
self.inf = 5.0 # For top radius
self.cls_embeddings = nn.Embedding( nb_classes, embedding_size + 1)
self.rel_embeddings = nn.Embedding( nb_relations, embedding_size + 1)
def load_eval_data(data_file):
data = []
rel = f'SubClassOf'
with open(data_file, 'r') as f:
for line in f:
it = line.strip().split()
id1 = it[0]
id2 = it[1]
data.append((id1, id2))
return data
def evaluate_hits(data,cls_embeds_file, embedding_size, batch_size, margin, reg_norm):
with open(cls_embeds_file, 'rb') as f:
cls_df = pkl.load(f)
nb_classes = len(cls_df['cls'])
nb_relations = len(cls_df['rel'])
model = ELModel(nb_classes, nb_relations, embedding_size, batch_size, margin, reg_norm).cuda()
model.load_state_dict(cls_df['embeddings'])
model.eval()
embeds_list = model.cls_embeddings(torch.tensor(list(range(nb_classes))).cuda())
# print(list(range(nb_classes)))
# embeds_list = cls_df['embeddings'].values
# classes = {v: k for k, v in enumerate(cls_df['classes'])}
classes = cls_df['classes']
rel = model.rel_embeddings(torch.tensor(0).cuda()).detach().cpu().numpy()
rel = rel[:-1]
embeds_list = embeds_list.detach().cpu().numpy()
size = len(embeds_list[0])
# embeds = np.zeros((nb_classes, size), dtype=np.float32)
# for i, emb in enumerate(embeds_list):
# embeds[i, :] = emb
embeds = embeds_list
embeds = embeds[:, :-1]
# print(classes)
top1 = 0
top10 = 0
top100 = 0
mean_rank = 0
rank_vals =[]
for test_pts in data:
c = test_pts[0]
d = test_pts[1]
index_c = classes[c]
index_d = classes[d]
dist = np.linalg.norm(embeds - embeds[index_d], axis=1)
dist_dict = {i: dist[i] for i in range(0, len(dist))}
s_dst = dict(sorted(dist_dict.items(), key=operator.itemgetter(1)))
s_dst_keys = list(s_dst.keys())
ranks_dict = { s_dst_keys[i]: i for i in range(0, len(s_dst_keys))}
rank_c = ranks_dict[index_c]
mean_rank += rank_c
rank_vals.append(rank_c)
if rank_c == 1:
top1 += 1
if rank_c <= 10:
top10 += 1
if rank_c <= 100:
top100 += 1
n = len(data)
top1 /= n
top10 /= n
top100 /= n
mean_rank /= n
total_classes = len(embeds)
return top1,top10,top100,mean_rank,rank_vals,total_classes
def compute_rank_percentile(scores,x):
scores.sort()
per = np.percentile(scores,x)
return per
import statistics
def compute_median_rank(rank_list):
med = np.median(rank_list)
return med
def calculate_percentile_1000(scores):
ranks_1000=[]
for item in scores:
if item < 1000:
ranks_1000.append(item)
n_1000 = len(ranks_1000)
nt = len(scores)
percentile = (n_1000/nt)*100
return percentile
def compute_rank_roc(ranks, n):
auc_lst = list(ranks.keys())
auc_x = auc_lst[1:]
auc_x.sort()
auc_y = []
tpr = 0
sum_rank = sum(ranks.values())
for x in auc_x:
tpr += ranks[x]
auc_y.append(tpr / sum_rank)
auc_x.append(n)
auc_y.append(1)
auc = np.trapz(auc_y, auc_x)/n
return auc
def out_results(rks_vals):
med_rank = compute_median_rank(rks_vals)
print("Median Rank:",med_rank)
per_rank_90 = compute_rank_percentile(rks_vals,90)
print("90th percentile rank:",per_rank_90)
percentile_below1000 = calculate_percentile_1000(rks_vals)
print("Percentile for below 1000:",percentile_below1000)
print("% Cases with rank greater than 1000:",(100 - percentile_below1000))
def print_results(rks_vals,n):
print("top1:",top1)
print("top10:",top10)
print("top100:",top100)
print("Mean Rank:",mean_rank)
rank_dicts = dict(Counter(rks_vals))
print("AUC:",compute_rank_roc(rank_dicts,n))
out_results(rks_vals)
tag='SNOMED'
AEL_dir = 'experiments/results/'
test_file = 'experiments/data/'+tag+'/'+tag+'_test.txt'
test_data = load_eval_data(test_file)
margin = -0.1
embedding_size = 100
batch_size = 256
reg_norm=1
learning_rate=3e-4
cls_embeds_file = AEL_dir+tag+'_{'+str(embedding_size)+'}_{'+str(margin)+'}_{1000}.pkl'
print('start evaluation........')
top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file,embedding_size,batch_size,margin,reg_norm)
print("EmEL Results on test data")
print_results(rank_vals,n_cls)
# # In[98]:
# # tag='GALEN'
# # AEL_dir = f'{tag}/EL/'
# # test_file = f'{tag}/{tag}_test.txt'
# # test_data = load_eval_data(test_file)
# # margin = 0
# # embedding_size = 50
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # # In[88]:
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[91]:
# # print("EL Results on test data")
# # print_results(rank_vals,n_cls)
# # # GALEN Evaluation on Inferences
# # In[15]:
# tag='GALEN'
# AEL_dir = f'{tag}/EmEL/'
# test_file = f'{tag}/{tag}_inferences.txt'
# test_data = load_eval_data(test_file)
# margin = 0
# embedding_size = 50
# batch_size = 256
# device='gpu:0'
# reg_norm=1
# learning_rate=3e-4
# cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_150_cls.pkl'
# top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file,embedding_size,batch_size,margin,reg_norm)
# # In[16]:
# ###50,0
# print("==========EmEL Results on Inferences data=========")
# print_results(rank_vals,n_cls)
# # In[102]:
# # tag='GALEN'
# # AEL_dir = f'{tag}/EL/'
# # test_file = f'{tag}/{tag}_inferences.txt'
# # test_data = load_eval_data(test_file)
# # margin = 0
# # embedding_size = 50
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[103]:
# # print("==========EL Results on Inferences data=========")
# # print_results(rank_vals,n_cls)
# # # GO Hits Evaluation on Test Data
# # In[17]:
# tag='GO'
# AEL_dir = f'{tag}/EmEL/'
# test_file = f'{tag}/{tag}_test.txt'
# test_data = load_eval_data(test_file)
# margin = -0.1
# embedding_size = 100
# batch_size = 256
# device='gpu:0'
# reg_norm=1
# learning_rate=3e-4
# cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_150_cls.pkl'
# top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file,embedding_size,batch_size,margin,reg_norm)
# # In[18]:
# ####100,-0.1
# print("==========EmEL Results on Test data=========")
# print_results(rank_vals,n_cls)
# # In[19]:
# # tag='GO'
# # AEL_dir = f'{tag}/EL/'
# # test_file = f'{tag}/{tag}_test.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 100
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[20]:
# # ##100,-0.1
# # print("==========EL Results on Test data=========")
# # print_results(rank_vals,n_cls)
# # # GO Evaluation on Inferences
# # In[21]:
# tag='GO'
# AEL_dir = f'{tag}/EmEL/'
# test_file = f'{tag}/{tag}_inferences.txt'
# test_data = load_eval_data(test_file)
# margin = -0.1
# embedding_size = 100
# batch_size = 256
# device='gpu:0'
# reg_norm=1
# learning_rate=3e-4
# cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_150_cls.pkl'
# top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file,embedding_size,batch_size,margin,reg_norm)
# # In[22]:
# ###100,-0.1
# print("==========EmEL Results on Inferences data=========")
# print_results(rank_vals,n_cls)
# # In[23]:
# # tag='GO'
# # AEL_dir = f'{tag}/EL/'
# # test_file = f'{tag}/{tag}_inferences.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 100
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[24]:
# # ####100,-0.1
# # print("==========EL Results on Inferences data=========")
# # print_results(rank_vals,n_cls)
# # # # Anatomy on Test Data
# # # In[8]:
# # tag='ANATOMY'
# # AEL_dir = f'{tag}/EmEL/'
# # test_file = f'{tag}/{tag}_test.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 200
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[9]:
# # ##200,-0.1
# # print("==========EmEL Results on Test data=========")
# # print_results(rank_vals,n_cls)
# # # In[10]:
# # tag='ANATOMY'
# # AEL_dir = f'{tag}/EL/'
# # test_file = f'{tag}/{tag}_test.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 200
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[11]:
# # ###200,-0.1
# # print("==========EL Results on Test data=========")
# # print_results(rank_vals,n_cls)
# # # # Anatomy on Inferences Data
# # # In[12]:
# # tag='ANATOMY'
# # AEL_dir = f'{tag}/EmEL/'
# # test_file = f'{tag}/{tag}_inferences.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 200
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[13]:
# # ##200,-0.1
# # print("==========EmEL Results on Inferences data=========")
# # print_results(rank_vals,n_cls)
# # # In[14]:
# # tag='ANATOMY'
# # AEL_dir = f'{tag}/EL/'
# # test_file = f'{tag}/{tag}_inferences.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 200
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[15]:
# # ###200,-0.1
# # print("==========EL Results on Inferences data=========")
# # print_results(rank_vals,n_cls)
# # # # SNOMED on Test Data
# # # In[8]:
# # tag='SNOMED'
# # AEL_dir = f'{tag}/EmEL/'
# # test_file = f'{tag}/{tag}_test.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 100
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # print("==========EmEL Results on Test data=========")
# # print_results(rank_vals,n_cls)
# # tag='SNOMED'
# # AEL_dir = f'{tag}/EL/'
# # test_file = f'{tag}/{tag}_test.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 100
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # print("==========EL Results on Test data=========")
# # print_results(rank_vals,n_cls)
# # # # SNOMED on Inferences
# # tag='SNOMED'
# # AEL_dir = f'{tag}/EmEL/'
# # test_file = f'{tag}/{tag}_inferences.txt'
# # test_data = load_eval_data(test_file)
# # margin = -0.1
# # embedding_size = 100
# # batch_size = 256
# # device='gpu:0'
# # reg_norm=1
# # learning_rate=3e-4
# # cls_embeds_file = AEL_dir + f'{tag}_{embedding_size}_{margin}_1000_cls.pkl'
# # test_data = test_data[0:12590]
# # top1,top10,top100,mean_rank,rank_vals,n_cls = evaluate_hits(test_data,cls_embeds_file)
# # # In[12]:
# # print("==========EmEL Results on Inferences data=========")
# # print_results(rank_vals,n_cls)