Skip to content

Instantly share code, notes, and snippets.

@frenzy2106
Last active December 22, 2021 07:17
Show Gist options
  • Save frenzy2106/307216435cfea07f23c082ed9aea6476 to your computer and use it in GitHub Desktop.
Save frenzy2106/307216435cfea07f23c082ed9aea6476 to your computer and use it in GitHub Desktop.
Mean Average Precision @ K
def apk(actual, predicted, k=3):
"""
Computes the average precision at k.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
actual : list
A list of elements that are to be predicted (order doesn't matter)
predicted : list
A list of predicted elements (order does matter)
k : int, optional
The maximum number of predicted elements
Returns
-------
score : double
The average precision at k over the input lists
"""
actual = list(actual)
predicted = list(predicted)
if len(predicted)>k:
predicted = predicted[:k]
score = 0.0
num_hits = 0.0
for i,p in enumerate(predicted):
if p in actual and p not in predicted[:i]:
num_hits += 1.0
score += num_hits / (i+1.0)
if not actual:
return 0.0
return score / min(len(actual), k)
def mapk(actual, predicted, k=3):
"""
Computes the mean average precision at k.
This function computes the mean average prescision at k between two lists
of lists of items.
Parameters
----------
actual : list
A list of lists of elements that are to be predicted
(order doesn't matter in the lists)
predicted : list
A list of lists of predicted elements
(order matters in the lists)
k : int, optional
The maximum number of predicted elements
Returns
-------
score : double
The mean average precision at k over the input lists
"""
return np.mean([apk(a,p,k) for a,p in zip(actual, predicted)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment