Update handler.py
Browse files- handler.py +2 -26
handler.py
CHANGED
@@ -3,6 +3,7 @@ import pickle
|
|
3 |
import numpy as np
|
4 |
import pandas as pd
|
5 |
import os
|
|
|
6 |
|
7 |
class ContentBasedRecommender:
|
8 |
def __init__(self, train_data):
|
@@ -15,38 +16,13 @@ class ContentBasedRecommender:
|
|
15 |
|
16 |
return np.random.choice(recommended_books, size=k, replace=False) if len(recommended_books) >= k else recommended_books
|
17 |
|
18 |
-
def evaluate(self, test_data, k=10):
|
19 |
-
user_ids = test_data['user_id'].unique()
|
20 |
-
hit_rate, ndcg_scores = [], []
|
21 |
-
|
22 |
-
for user_id in user_ids[:100]:
|
23 |
-
true_books = set(test_data[test_data['user_id'] == user_id]['book_id'])
|
24 |
-
pred_books = set(self.predict(user_id, k))
|
25 |
-
|
26 |
-
hits = len(true_books & pred_books)
|
27 |
-
hit_rate.append(hits / min(k, len(true_books)))
|
28 |
-
|
29 |
-
dcg = sum(1 / math.log2(rank + 2) for rank, book in enumerate(pred_books) if book in true_books)
|
30 |
-
idcg = sum(1 / math.log2(i + 2) for i in range(min(k, len(true_books))))
|
31 |
-
ndcg = dcg / idcg if idcg > 0 else 0
|
32 |
-
ndcg_scores.append(ndcg)
|
33 |
-
|
34 |
-
return np.mean(hit_rate), np.mean(ndcg_scores)
|
35 |
-
|
36 |
class EndpointHandler:
|
37 |
def __init__(self, path=""):
|
38 |
model_path = os.path.join(path, "model.pkl")
|
39 |
with open(model_path, 'rb') as f:
|
40 |
-
self.model =
|
41 |
|
42 |
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
43 |
-
"""
|
44 |
-
data args:
|
45 |
-
user_id (:obj: `str` or `int`)
|
46 |
-
k (:obj: `int`, optional)
|
47 |
-
Return:
|
48 |
-
A :obj:`list` of :obj:`dict`: will be serialized and returned
|
49 |
-
"""
|
50 |
user_id = data.pop("user_id", None)
|
51 |
k = data.pop("k", 10) # Default to 10 if not provided
|
52 |
|
|
|
3 |
import numpy as np
|
4 |
import pandas as pd
|
5 |
import os
|
6 |
+
import dill
|
7 |
|
8 |
class ContentBasedRecommender:
|
9 |
def __init__(self, train_data):
|
|
|
16 |
|
17 |
return np.random.choice(recommended_books, size=k, replace=False) if len(recommended_books) >= k else recommended_books
|
18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
class EndpointHandler:
|
20 |
def __init__(self, path=""):
|
21 |
model_path = os.path.join(path, "model.pkl")
|
22 |
with open(model_path, 'rb') as f:
|
23 |
+
self.model = dill.load(f)
|
24 |
|
25 |
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
user_id = data.pop("user_id", None)
|
27 |
k = data.pop("k", 10) # Default to 10 if not provided
|
28 |
|