-
Notifications
You must be signed in to change notification settings - Fork 0
/
popularity.py
60 lines (48 loc) · 1.76 KB
/
popularity.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Popularity baseline
"""
import numpy as np
from spotlight.factorization._components import _predict_process_ids
from utils import most_common
class PopularityModel(object):
def __init__(self,
k=20):
self.k = 20
self.topk = []
self.flag = False
def fit(self, interactions, verbose=False):
self.topk = most_common(interactions.item_ids, 20)
self.num_items = interactions.num_items
def predict(self, user_ids, item_ids=None):
"""
Make predictions: given a user id, compute the recommendation
scores for items.
Parameters
----------
user_ids: int or array
If int, will predict the recommendation scores for this
user for all items in item_ids. If an array, will predict
scores for all (user, item) pairs defined by user_ids and
item_ids.
item_ids: array, optional
Array containing the item ids for which prediction scores
are desired. If not supplied, predictions for all items
will be computed.
Returns
-------
predictions: np.array
Predicted scores for all items in item_ids.
"""
if not self.flag:
user_ids, item_ids = _predict_process_ids(user_ids, item_ids,
self.num_items,
False)
outs = []
for item in item_ids:
if int(item) in self.topk:
outs.append(float(1/(self.topk.index(int(item))+1)))
else:
outs.append(0.0)
self.topk = np.array(outs)
self.flag = True
return self.topk