-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.py
525 lines (432 loc) · 20 KB
/
metrics.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
import numpy as np
from myutils import *
from easydict import EasyDict as edict
def dcg_at_k(r, k, method=1):
r = np.asfarray(r)[:k]
if r.size:
if method == 0:
return r[0] + np.sum(r[1:] / np.log2(np.arange(2, r.size + 1)))
elif method == 1:
return np.sum(r / np.log2(np.arange(2, r.size + 2)))
else:
raise ValueError('method must be 0 or 1.')
return 0.
def ndcg_at_k(r, k, method=0):
dcg_max = dcg_at_k(sorted(r, reverse=True), k, method)
if not dcg_max:
return 0.
return dcg_at_k(r, k, method) / dcg_max
def measure_rec_quality(path_data):
# Evaluate only the attributes that have been chosen and are avaiable in the chosen dataset
flags = path_data.sens_attribute_flags
attribute_list = get_attribute_list(path_data.dataset_name, flags)
metrics_names = ["ndcg", "hr", "recall", "precision"]
metrics = edict()
for metric in metrics_names:
metrics[metric] = {"Overall": []}
for values in attribute_list.values():
if len(attribute_list) == 1: break
attribute_to_name = values[1]
for _, name in attribute_to_name.items():
metrics[metric][name] = []
topk_matches = path_data.uid_topk
test_labels = path_data.test_labels
test_user_idxs = list(test_labels.keys())
invalid_users = []
for uid in test_user_idxs:
if uid not in topk_matches: continue
if len(topk_matches[uid]) < 10:
invalid_users.append(uid)
continue
pred_list, rel_set = topk_matches[uid], test_labels[uid]
if len(pred_list) == 0:
continue
k = 0
hit_num = 0.0
hit_list = []
for pid in pred_list:
k += 1
if pid in rel_set:
hit_num += 1
hit_list.append(1)
else:
hit_list.append(0)
ndcg = ndcg_at_k(hit_list, k)
recall = hit_num / len(rel_set)
precision = hit_num / len(pred_list)
hit = 1.0 if hit_num > 0.0 else 0.0
# Based on attribute
for attribute in attribute_list.keys():
if uid not in attribute_list[attribute][0]: continue
attr_value = attribute_list[attribute][0][uid]
if attr_value not in attribute_list[attribute][1]: continue #Few users may have the attribute missing (LASTFM)
attr_name = attribute_list[attribute][1][attr_value]
metrics["ndcg"][attr_name].append(ndcg)
metrics["recall"][attr_name].append(recall)
metrics["precision"][attr_name].append(precision)
metrics["hr"][attr_name].append(hit)
metrics["ndcg"]["Overall"].append(ndcg)
metrics["recall"]["Overall"].append(recall)
metrics["precision"]["Overall"].append(precision)
metrics["hr"]["Overall"].append(hit)
return metrics
def print_rec_metrics(dataset_name, flags, metrics):
attribute_list = get_attribute_list(dataset_name, flags)
print("\n---Recommandation Quality---")
print("Average for the entire user base:", end=" ")
for metric, values in metrics.items():
print("{}: {:.3f}".format(metric, np.array(values["Overall"]).mean()), end=" | ")
print("")
for attribute_category, values in attribute_list.items():
print("\n-Statistic with user grouped by {} attribute".format(attribute_category))
for attribute in values[1].values():
print("{} group".format(attribute), end=" ")
for metric_name, groups_values in metrics.items():
print("{}: {:.3f}".format(metric_name, np.array(groups_values[attribute]).mean()), end=" | ")
print("")
print("\n")
"""
Explanation metrics
"""
def topk_ETV(path_data):
dataset_name = path_data.dataset_name
def simpson_index(topk):
n_path_for_patterns = {k: 0 for k in set(PATH_TYPES[dataset_name])}
N = 0
for path in topk:
path = path
path_type = get_path_type(path)
if path_type == 'self_loop':
path_type = 'described_as'
n_path_for_patterns[path_type] += 1
N += 1
numerator = 0
for path_type, n_path_type_ith in n_path_for_patterns.items():
numerator += n_path_type_ith * (n_path_type_ith - 1)
# N = 0
# for item_path in pred_uv_paths.items():
# N += len(item_path[1])
if N * (N - 1) == 0:
return 0
return 1 - (numerator / (N * (N - 1)))
ETVs = {}
for uid, topk in path_data.uid_topk.items():
if uid not in path_data.test_labels: continue
ETV = simpson_index([path_data.uid_pid_explanation[uid][pid] for pid in topk])
ETVs[uid] = ETV
return ETVs
def avg_ETV(path_data):
uid_ETVs = topk_ETV(path_data)
# Evaluate only the attributes that have been chosen and are avaiable in the chosen dataset
flags = path_data.sens_attribute_flags
attribute_list = get_attribute_list(path_data.dataset_name, flags)
avg_groups_ETV = {}
groups_ETV_scores = {}
# Initialize group scores with empty list
for attribute in attribute_list.keys():
for _, attribute_label in attribute_list[attribute][1].items():
groups_ETV_scores[attribute_label] = []
if "Overall" not in groups_ETV_scores:
groups_ETV_scores["Overall"] = []
for uid, ETV in uid_ETVs.items():
for attribute in attribute_list.keys():
if uid not in attribute_list[attribute][0]: continue
attr_value = attribute_list[attribute][0][uid]
if attr_value not in attribute_list[attribute][1]: continue # Few users may have the attribute missing (LASTFM)
attr_name = attribute_list[attribute][1][attr_value]
groups_ETV_scores[attr_name].append(ETV)
groups_ETV_scores["Overall"].append(ETV)
for attribute_label, group_scores in groups_ETV_scores.items():
avg_groups_ETV[attribute_label] = np.array(group_scores).mean()
explanation_type_variety = edict(
avg_groups_ETV=avg_groups_ETV,
groups_ETV_scores=groups_ETV_scores
)
return explanation_type_variety
def avg_LID(path_data):
uid_LIDs = topk_LID(path_data)
# Evaluate only the attributes that have been chosen and are avaiable in the chosen dataset
flags = path_data.sens_attribute_flags
attribute_list = get_attribute_list(path_data.dataset_name, flags)
avg_groups_LID = {}
groups_LID_scores = {}
# Initialize group scores with empty list
for attribute in attribute_list.keys():
for _, attribute_label in attribute_list[attribute][1].items():
groups_LID_scores[attribute_label] = []
if "Overall" not in groups_LID_scores:
groups_LID_scores["Overall"] = []
for uid, LID in uid_LIDs.items():
for attribute in attribute_list.keys():
if uid not in attribute_list[attribute][0]: continue
attr_value = attribute_list[attribute][0][uid]
if attr_value not in attribute_list[attribute][1]: continue #Few users may have the attribute missing (LASTFM)
attr_name = attribute_list[attribute][1][attr_value]
groups_LID_scores[attr_name].append(LID)
groups_LID_scores["Overall"].append(LID)
for attribute_label, group_scores in groups_LID_scores.items():
avg_groups_LID[attribute_label] = np.array(group_scores).mean()
linked_interaction_diversity_results = edict(
avg_groups_LID=avg_groups_LID,
groups_LID_scores=groups_LID_scores
)
return linked_interaction_diversity_results
def topk_LID(path_data):
LIDs = {}
for uid, topk in path_data.uid_topk.items():
if uid not in path_data.test_labels: continue
unique_linked_interaction = set()
count = 0
for pid in topk:
if pid not in path_data.uid_pid_explanation[uid]:
continue
current_path = path_data.uid_pid_explanation[uid][pid]
li = get_linked_interaction_id(current_path)
if current_path[1][0] == "mention":
li += 10000 #pad in order to not make them overlap, this is a stupid workaround, fix it
unique_linked_interaction.add(li)
if len(topk) == 0 or len(unique_linked_interaction) == 0:
count += 1
LID = len(unique_linked_interaction) / len(topk)
LIDs[uid] = LID
print(count)
return LIDs
def avg_SED(path_data):
uid_SEDs = topk_SED(path_data)
# Evaluate only the attributes that have been chosen and are avaiable in the chosen dataset
flags = path_data.sens_attribute_flags
attribute_list = get_attribute_list(path_data.dataset_name, flags)
avg_groups_SED = {}
groups_SED_scores = {}
# Initialize group scores with empty list
for attribute in attribute_list.keys():
for _, attribute_label in attribute_list[attribute][1].items():
groups_SED_scores[attribute_label] = []
if "Overall" not in groups_SED_scores:
groups_SED_scores["Overall"] = []
for uid, SED in uid_SEDs.items():
for attribute in attribute_list.keys():
if uid not in attribute_list[attribute][0]: continue
attr_value = attribute_list[attribute][0][uid]
if attr_value not in attribute_list[attribute][1]: continue #Few users may have the attribute missing (LASTFM)
attr_name = attribute_list[attribute][1][attr_value]
groups_SED_scores[attr_name].append(SED)
groups_SED_scores["Overall"].append(SED)
for attribute_label, group_scores in groups_SED_scores.items():
avg_groups_SED[attribute_label] = np.array(group_scores).mean()
shared_entity_diversity_results = edict(
avg_groups_SED=avg_groups_SED,
groups_SED_scores=groups_SED_scores
)
return shared_entity_diversity_results
def topk_SED(path_data):
SEDs = {}
for uid, topk in path_data.uid_topk.items():
if uid not in path_data.test_labels: continue
unique_shared_entities = set()
for pid in topk:
if pid not in path_data.uid_pid_explanation[uid]:
continue
current_path = path_data.uid_pid_explanation[uid][pid]
se = get_shared_entity_id(current_path)
unique_shared_entities.add(se)
if len(topk) > 0:
SED = len(unique_shared_entities) / len(topk)
else:
SED = 1
SEDs[uid] = SED
return SEDs
def topk_ETD(path_data):
ETDs = {}
for uid, topk in path_data.uid_topk.items():
if uid not in path_data.test_labels: continue
unique_path_types = set()
for pid in topk:
if pid not in path_data.uid_pid_explanation[uid]:
continue
current_path = path_data.uid_pid_explanation[uid][pid]
path_type = get_path_type(current_path)
unique_path_types.add(path_type)
ETD = len(unique_path_types) / TOTAL_PATH_TYPES[path_data.dataset_name]
ETDs[uid] = ETD
return ETDs
def get_attribute_list(dataset_name, flags):
attribute_list = {}
for attribute, flag in flags.items():
if flag and DATASET_SENSIBLE_ATTRIBUTE_MATRIX[dataset_name][attribute]:
attribute_list[attribute] = []
for attribute in attribute_list.keys():
if attribute == "Gender":
user2attribute, attribute2name = get_kg_uid_to_gender_map(dataset_name)
elif attribute == "Age":
user2attribute, attribute2name = get_kg_uid_to_age_map(dataset_name)
elif attribute == "Occupation":
user2attribute, attribute2name = get_kg_uid_to_occupation_map(dataset_name)
elif attribute == "Country":
pass #implement country
else:
print("Unknown attribute")
attribute_list[attribute] = [user2attribute, attribute2name]
return attribute_list
def avg_ETD(path_data):
uid_ETDs = topk_ETD(path_data)
# Evaluate only the attributes that have been chosen and are avaiable in the chosen dataset
flags = path_data.sens_attribute_flags
attribute_list = get_attribute_list(path_data.dataset_name, flags)
avg_groups_ETD = {}
groups_ETD_scores = {}
# Initialize group scores with empty list
for attribute in attribute_list.keys():
for _, attribute_label in attribute_list[attribute][1].items():
groups_ETD_scores[attribute_label] = []
if "Overall" not in groups_ETD_scores:
groups_ETD_scores["Overall"] = []
for uid, ETD in uid_ETDs.items():
for attribute in attribute_list.keys():
if uid not in attribute_list[attribute][0]: continue
attr_value = attribute_list[attribute][0][uid]
if attr_value not in attribute_list[attribute][1]: continue #Few users may have the attribute missing (LASTFM)
attr_name = attribute_list[attribute][1][attr_value]
groups_ETD_scores[attr_name].append(ETD)
groups_ETD_scores["Overall"].append(ETD)
for attribute_label, group_scores in groups_ETD_scores.items():
avg_groups_ETD[attribute_label] = np.array(group_scores).mean()
diversity_results = edict(
avg_groups_ETD=avg_groups_ETD,
groups_ETD_scores=groups_ETD_scores
)
return diversity_results
#Extract the value of LIR for the given user item path from the LIR_matrix
def LIR_single(path_data, path):
uid = int(path[0][-1])
if uid not in path_data.uid_timestamp or uid not in path_data.LIR_matrix or len(path_data.uid_timestamp[uid]) <= 1: return 0. #Should not enter there
predicted_path = path
linked_interaction = int(get_interaction_id(predicted_path))
linked_interaction_type = get_interaction_type(predicted_path)
#Handle the case of Amazon Dataset where a path may have different interaction types
if linked_interaction_type == "mentions":
LIR = path_data.LIR_matrix_words[uid][linked_interaction]
elif linked_interaction_type == "watched" or linked_interaction_type == "listened" or linked_interaction_type == "purchase":
LIR = path_data.LIR_matrix[uid][linked_interaction]
else:
LIR = 0.
return LIR
# Returns a dict where to every uid is associated a value of LIR calculated based on his topk
def topk_LIR(path_data):
LIR_topk = {}
# Precompute user timestamps weigths
LIR_matrix = path_data.LIR_matrix
for uid in path_data.test_labels.keys(): #modified for pgpr labels
LIR_single_topk = []
if uid not in LIR_matrix or uid not in path_data.uid_topk:
continue
for pid in path_data.uid_topk[uid]:
predicted_path = path_data.uid_pid_explanation[uid][pid]
linked_interaction = int(get_interaction_id(predicted_path))
linked_interaction_type = get_interaction_type(predicted_path)
# Handle the case of Amazon Dataset where a path may have different interaction types
if linked_interaction_type == "mentions":
LIR = path_data.LIR_matrix_words[uid][linked_interaction]
elif linked_interaction_type == "purchase" or linked_interaction_type == "watched" or linked_interaction_type == "listened":
LIR = LIR_matrix[uid][linked_interaction]
else:
LIR = 0.
LIR_single_topk.append(LIR)
LIR_topk[uid] = np.array(LIR_single_topk).mean() if len(LIR_single_topk) != 0 else 0
return LIR_topk
# Returns an avg value for the LIR of a given group
def avg_LIR(path_data):
uid_LIR_score = topk_LIR(path_data)
avg_groups_LIR = {}
groups_LIR_scores = {}
# Evaluate only the attributes that have been chosen and are avaiable in the chosen dataset
flags = path_data.sens_attribute_flags
attribute_list = get_attribute_list(path_data.dataset_name, flags)
#Initialize group scores with empty list
for attribute in attribute_list.keys():
for _, attribute_label in attribute_list[attribute][1].items():
groups_LIR_scores[attribute_label] = []
if "Overall" not in groups_LIR_scores:
groups_LIR_scores["Overall"] = []
for uid, LIR_score in uid_LIR_score.items():
for attribute in attribute_list.keys():
if uid not in attribute_list[attribute][0]: continue
attr_value = attribute_list[attribute][0][uid]
if attr_value not in attribute_list[attribute][1]: continue #Few users may have the attribute missing (LASTFM)
attr_name = attribute_list[attribute][1][attr_value]
groups_LIR_scores[attr_name].append(LIR_score)
groups_LIR_scores["Overall"].append(LIR_score)
for attribute_label, group_scores in groups_LIR_scores.items():
avg_groups_LIR[attribute_label] = np.array(group_scores).mean()
LIR = edict(
avg_groups_LIR=avg_groups_LIR,
groups_LIR_scores=groups_LIR_scores,
)
return LIR
#Extract the value of SEP for the given user item path from the SEP_matrix
def SEP_single(path_data, path):
related_entity_type, related_entity_id = get_shared_entity(path)
SEP = path_data.SEP_matrix[related_entity_type][related_entity_id]
return SEP
def topks_SEP(path_data):
SEP_topk = {}
# Precompute entity distribution
exp_serendipity_matrix = path_data.SEP_matrix
#Measure explanation serendipity for topk
for uid in path_data.test_labels:
SEP_single_topk = []
if uid not in path_data.uid_topk: continue
for pid in path_data.uid_topk[uid]:
if pid not in path_data.uid_pid_explanation[uid]:
#print("strano 2")
continue
path = path_data.uid_pid_explanation[uid][pid]
related_entity_type, related_entity_id = get_shared_entity(path)
SEP = exp_serendipity_matrix[related_entity_type][related_entity_id]
SEP_single_topk.append(SEP)
if len(SEP_single_topk) == 0: continue
SEP_topk[uid] = np.array(SEP_single_topk).mean()
return SEP_topk
def avg_SEP(path_data):
uid_SEP = topks_SEP(path_data)
avg_groups_SEP = {}
groups_SEP_scores = {}
# Evaluate only the attributes that have been chosen and are avaiable in the chosen dataset
flags = path_data.sens_attribute_flags
attribute_list = get_attribute_list(path_data.dataset_name, flags)
# Initialize group scores with empty list
for attribute in attribute_list.keys():
for _, attribute_label in attribute_list[attribute][1].items():
groups_SEP_scores[attribute_label] = []
if "Overall" not in groups_SEP_scores:
groups_SEP_scores["Overall"] = []
for uid, SEP_score in uid_SEP.items():
for attribute in attribute_list.keys():
if uid not in attribute_list[attribute][0]: continue
attr_value = attribute_list[attribute][0][uid]
if attr_value not in attribute_list[attribute][1]: continue #Few users may have the attribute missing (LASTFM)
attr_name = attribute_list[attribute][1][attr_value]
groups_SEP_scores[attr_name].append(SEP_score)
groups_SEP_scores["Overall"].append(SEP_score)
for attribute_label, group_scores in groups_SEP_scores.items():
avg_groups_SEP[attribute_label] = np.array(group_scores).mean()
serendipity_results = edict(
avg_groups_SEP=avg_groups_SEP,
groups_SEP_scores=groups_SEP_scores,
)
return serendipity_results
def print_expquality_metrics(dataset_name, flags, metric_values):
attribute_list = get_attribute_list(dataset_name, flags)
print("\n---Explanation Quality---")
print("Average for the entire user base:", end=" ")
for metric, values in metric_values.items():
print("{}: {:.3f}".format(metric, values["Overall"]), end= " | ")
print("")
for attribute_category, values in attribute_list.items():
attributes = values[1].values()
print("\n-Statistic with user grouped by {} attribute".format(attribute_category))
for attribute in attributes:
print("{} group".format(attribute), end=" ")
for metric, values in metric_values.items():
print("{}: {:.3f}".format(metric, values[attribute]), end=" | ")
print("")