def ItemSimilarity(self):
# 一个字典,记录 rui*ruj
# 一个字典 记录 rui^2
# 建立物品-物品的共现矩阵
item2item = dict() # 物品-物品的共现矩阵。记录rui*ruj,分子
buy = dict() # 物品被多少个不同用户进行过评分。记录rui*rui分母
for user, items in self.data.items():
for i in items.keys():
buy.setdefault(i, 0)
temp = items[i]*items[i]
buy[i] += temp
item2item.setdefault(i, {})
for j in items.keys():
if i == j: continue
item2item[i].setdefault(j, 0)
item2item[i][j] += items[i]*items[j]
# 计算相似度矩阵
self.similar_matrix = dict()
for i, related_items in item2item.items():
self.similar_matrix.setdefault(i, {})
for j, cij in related_items.items():
self.similar_matrix[i][j] = cij / (math.sqrt(buy[i]) * math.sqrt(buy[j]))
return self.similar_matrix