Skip to content
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
16 changes: 9 additions & 7 deletions Python/ml_metrics/average_precision.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import numpy as np


def apk(actual, predicted, k=10):
"""
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
Expand All @@ -22,33 +23,34 @@ def apk(actual, predicted, k=10):
The average precision at k over the input lists

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

score = 0.0
num_hits = 0.0

for i,p in enumerate(predicted):
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)
score += num_hits / (i + 1.0)

if not actual:
return 0.0

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


def mapk(actual, predicted, k=10):
"""
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
----------
actual : list
A list of lists of elements that are to be predicted
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
Expand All @@ -62,4 +64,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)])