给每一行代码增加注释:class TopNRecommend(): #初始化数据结构为[(用户id,新闻id,评分)] def init(self, data): data_dic = {} for line in data: if not line[0] in data_dic.keys(): data_dic[line[0]] = {line[1]: line[2]} else: data_dic[line[0]][line[1]] = line[2] self.data = data_dic self.ItemSimilarity() #计算相似的数据 def ItemSimilarity(self): self.itemSim = dict() movie_popular = dict() # item_user_count{item: likeCount} the number of users who like the item count = dict() # count{i:{j:value}} the number of users who both like item i and j # 计算每部新闻的相关度 # 先计算每件物品被喜欢的人次、物品关系矩阵C及相似度矩阵W,代码中分别为movie_popular,及过程中的itemSim和最终的itemSim。 #计算每个新闻的观看次数 for user, musics in self.data.items(): for movie in musics: if movie not in movie_popular: movie_popular[movie] = 0 movie_popular[movie] += 1 movie_count = len(movie_popular) print('Total musics: %d' % movie_count) print("musics count is:{}", movie_popular) # 计算物品关系矩阵 for user, musics in self.data.items(): for m1 in musics: for m2 in musics: if m1 == m2: continue self.itemSim.setdefault(m1, {}) self.itemSim[m1].setdefault(m2, 0) self.itemSim[m1][m2] += 1 / math.log(1 + len(musics)) print('Build co-rated users matrix success!')
时间: 2023-12-06 12:42:49 浏览: 82
#定义一个名为TopNRecommend的类
class TopNRecommend():
#初始化数据结构为[(用户id,新闻id,评分)]
def __init__(self, data):
data_dic = {}
#将数据转化为字典类型,键为用户id,值为该用户对新闻的评分
for line in data:
if not line[0] in data_dic.keys():
data_dic[line[0]] = {line[1]: line[2]}
else:
data_dic[line[0]][line[1]] = line[2]
self.data = data_dic
#计算每个新闻之间的相似性
self.ItemSimilarity()
#计算每个新闻之间的相似性
def ItemSimilarity(self):
#存储新闻之间的相似度
self.itemSim = dict()
#存储每个新闻的流行度
movie_popular = dict()
#存储每个新闻被喜欢的人次数
count = dict()
#计算每个新闻的观看次数
for user, musics in self.data.items():
for movie in musics:
if movie not in movie_popular:
movie_popular[movie] = 0
movie_popular[movie] += 1
movie_count = len(movie_popular)
print('Total musics: %d' % movie_count)
print("musics count is:{}", movie_popular)
#计算物品关系矩阵
for user, musics in self.data.items():
for m1 in musics:
for m2 in musics:
if m1 == m2:
continue
self.itemSim.setdefault(m1, {})
self.itemSim[m1].setdefault(m2, 0)
#计算物品关系矩阵中的每个元素的值
self.itemSim[m1][m2] += 1 / math.log(1 + len(musics))
print('Build co-rated users matrix success!')
阅读全文