Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix average precision at k calculation #54

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 18 additions & 19 deletions Python/ml_metrics/average_precision.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,47 @@
import numpy as np

def apk(actual, predicted, k=10):

def apk(actual: list, predicted: list, k=10) -> float:
"""
Computes the average precision at k.

This function computes the average prescision at k between two lists of
This function computes the average precision at k between two lists of
items.

Parameters
----------
actual : list
A list of elements that are to be predicted (order doesn't matter)
A list of elements that are to be predicted
predicted : list
A list of predicted elements (order does matter)
A list of predicted elements (order does matter)
k : int, optional
The maximum number of predicted elements

Returns
-------
score : double
score : float
The average precision at k over the input lists

"""
if len(predicted)>k:
if len(predicted) > k:
predicted = predicted[:k]

score = 0.0
sum_precision = 0.0
num_hits = 0.0

for i,p in enumerate(predicted):
if p in actual and p not in predicted[:i]:
for i, prediction in enumerate(predicted):
if prediction in actual[:k] and prediction not in predicted[:i]:
num_hits += 1.0
score += num_hits / (i+1.0)
precision_at_i = num_hits / (i + 1.0)
sum_precision += precision_at_i

if not actual:
if num_hits == 0.0:
return 0.0

return score / min(len(actual), k)
return sum_precision / num_hits


def mapk(actual, predicted, k=10):
def mapk(actual: list, predicted: list, k=10) -> float:
"""
Computes the mean average precision at k.

This function computes the mean average prescision at k between two lists
This function computes the mean average precision at k between two lists
of lists of items.

Parameters
Expand All @@ -62,4 +61,4 @@ def mapk(actual, predicted, k=10):
The mean average precision at k over the input lists

"""
return np.mean([apk(a,p,k) for a,p in zip(actual, predicted)])
return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)])