Created
January 8, 2019 09:15
-
-
Save fufufukakaka/9c472521c06a57d3804119d5b2fbd8ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def precision_and_recall(ranked_list, ground_list): | |
hits = 0 | |
for i in range(len(ranked_list)): | |
id = ranked_list[i] | |
if id in ground_list: | |
hits += 1 | |
pre = hits / (1.0 * len(ranked_list)) | |
rec = hits / (1.0 * len(ground_list)) | |
return pre, rec | |
def AP(ranked_list, ground_truth): | |
hits, sum_precs = 0, 0.0 | |
for i in range(len(ranked_list)): | |
id = ranked_list[i] | |
if id in ground_truth: | |
hits += 1 | |
sum_precs += hits / (i + 1.0) | |
if hits > 0: | |
return sum_precs / len(ground_truth) | |
else: | |
return 0.0 | |
def RR(ranked_list, ground_list): | |
for i in range(len(ranked_list)): | |
id = ranked_list[i] | |
if id in ground_list: | |
return 1 / (i + 1.0) | |
return 0 | |
def nDCG(ranked_list, ground_truth): | |
dcg = 0 | |
idcg = IDCG(len(ground_truth)) | |
for i in range(len(ranked_list)): | |
id = ranked_list[i] | |
if id not in ground_truth: | |
continue | |
rank = i + 1 | |
dcg += 1 / math.log(rank + 1, 2) | |
return dcg / idcg | |
def IDCG(n): | |
idcg = 0 | |
for i in range(n): | |
idcg += 1 / math.log(i + 2, 2) | |
return idcg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment