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

Map metric #71

Open
wants to merge 2 commits 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
47 changes: 47 additions & 0 deletions spotlight/evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,53 @@ def mrr_score(model, test, train=None):
return np.array(mrrs)


def map_score(model, test, train=None):
"""
Compute mean average precision (MAP) scores.
Calculates the average precision for each user's recommendation vector,
then computes the resultant mean for all users.

Parameters
----------

model: fitted instance of a recommender model
The model to evaluate.
test: :class:`spotlight.interactions.Interactions`
Test interactions.
train: :class:`spotlight.interactions.Interactions`, optional
Train interactions. If supplied, scores of known
interactions will be set to very low values and so not
affect the MAP.

Returns
-------

map score: float
the MAP score
"""

test = test.tocsr()
if train is not None:
train = train.tocsr()

ap = []

for user_id, row in enumerate(test):
if not len(row.indices):
continue
predictions = -model.predict(user_id)
if train is not None:
predictions[train[user_id].indices] = FLOAT_MAX

prec = []
ranking = np.sort(st.rankdata(predictions)[row.indices])
for index, value in enumerate(ranking):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could probably do prec = np.arange(1, len(ranking) + 1) / ranking or something similar to make use of vectorized numpy operations?

prec.append((index + 1) / value)
ap.append(sum(prec) / len(ranking))

return np.mean(ap)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other metrics return raw arrays, leaving the averaging (or getting other descriptive statistics) down to the user. Could we do it this way here as well?



def sequence_mrr_score(model, test, exclude_preceding=False):
"""
Compute mean reciprocal rank (MRR) scores. Each sequence
Expand Down