前面的两篇是基于用户的推荐, 但是当物品很多的时候就显得很慢了, 所以就有了基于物品的推荐, 好处就是提前算好任何两件物品的相似度, 这样就可以节省大量的运算(只需要定期更新物品之间的关系)
#!/usr/bin/env python
#coding=GBK
import chardet
from math import sqrt
import urllib
import pydelicious as pdl
#电影打分, ltl对a电影打了4.3分.....
critics = {'ltl':{'a':4.3, 'b': 3.5, 'c': 4.7}
,'oyl':{'a': 4.3, 'b': 3.5, 'd': 3.0, 'e':4.2}
,'ygq':{'b': 3.2, 'c': 2.7, 'd': 4.1, 'f':2.1}
,'mmm':{'a': 2.3, 'd': 4.3, 'e': 1.9}
}
#求person1, 和perso2之间的相似度
def sim_distance(prefs, dianying, dianying2):
dis = 0
for item in prefs[dianying]:
if item in prefs[dianying2]:
dis += (pow(prefs[dianying][item] - prefs[dianying2][item], 2))
return 1 / (1 + sqrt(dis))
#跟电影相似的其他前n个电影
def topMatchs(prefs, item, n = 5, similarity = sim_distance):
scores = [(similarity(prefs, item, other), other)for other in prefs if other != item]
scores.sort()
scores.reverse()
return scores[0:n]
#将prefs里面的主副导致, 比如电影a, 有ltl给了4.3分, oyl给了4.3分, mmm给了2.3分
def transformPrefs(prefs):
results = {}
for person in prefs:
for item in prefs[person]:
results.setdefault(item, {})
results[item][person] = prefs[person][item]
return results
#计算任意两部电影之间的相似度
def calculateSimilarItems(prefs, n = 10):
result = {}
itemPrefs = transformPrefs(prefs)
c = 0
for item in itemPrefs:
c += 1
if c % 100 == 0:
print "%d / %d" %(c, len(itemPrefs))
scores = topMatchs(itemPrefs, item, 10, sim_distance)
result[item] = scores
return result
#基于物品的协作性过滤,这样的好处就是可以提前计算好任何两件物品的相关度, 从而提速
def getRecommendedItems(prefs, itemMatch, user):
scores = {}
simSums = {}
for (item, rating) in prefs[user].items():
for (similarity, item2) in itemMatch[item]:
if item2 in prefs[user]:
continue
simSums.setdefault(item2, 0)
simSums[item2] += similarity
scores.setdefault(item2, 0)
scores[item2] += (rating * similarity)
rankings = [(score / simSums[item], item) for item, score in scores.items()]
rankings.sort()
rankings.reverse()
return rankings
itemSim = calculateSimilarItems(critics, 10)
print getRecommendedItems(critics, itemSim, 'ltl')