recommender.py
3 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
"""
recommender - python module for classes related to recommenders.
"""
__author__ = "Tassia Camoes Araujo <tassia@gmail.com>"
__copyright__ = "Copyright (C) 2011 Tassia Camoes Araujo"
__license__ = """
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import xapian
import operator
import data
import strategy
class RecommendationResult:
"""
Class designed to describe a recommendation result: items and scores.
"""
def __init__(self,item_score):
"""
Set initial parameters.
"""
self.item_score = item_score
self.size = len(item_score)
def __str__(self):
"""
String representation of the object.
"""
result = self.get_prediction()
str = "\n"
for i in range(len((list(result)))):
str += "%2d: %s\n" % (i,result[i][0])
return str
def get_prediction(self,limit=0):
"""
Return prediction based on recommendation size (number of items).
"""
sorted_result = sorted(self.item_score.items(),
key=operator.itemgetter(1))
if not limit or limit > self.size:
limit = self.size
return list(reversed(sorted_result[-limit:]))
class Recommender:
"""
Class designed to play the role of recommender.
"""
def __init__(self,cfg):
"""
Set initial parameters.
"""
self.items_repository = xapian.Database(cfg.axi)
self.set_strategy(cfg.strategy)
if cfg.weight == "bm25":
self.weight = xapian.BM25Weight()
else:
self.weight = xapian.TradWeight()
self.cfg = cfg
def set_strategy(self,strategy_str):
"""
Set the recommendation strategy.
"""
if strategy_str == "cb":
self.strategy = strategy.ContentBasedStrategy("full")
if strategy_str == "cbt":
self.strategy = strategy.ContentBasedStrategy("tag")
if strategy_str == "cbd":
self.strategy = strategy.ContentBasedStrategy("desc")
if strategy_str == "col":
self.strategy = strategy.CollaborativeStrategy(20)
self.users_repository = data.PopconXapianIndex(self.cfg)
def get_recommendation(self,user,result_size=20):
"""
Produces recommendation using previously loaded strategy.
"""
return self.strategy.run(self,user,result_size)