这是 recommendations.py Programming Collective Intelligence Book Chapter 2 的代码。
下面的代码是从偏好字典中返回最匹配的人,并通过使用每个其他用户排名的加权平均值来获得对人的推荐
from math import sqrt
critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,'The Night Listener': 3.0},'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,'You, Me and Dupree': 3.5},'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,'Superman Returns': 3.5, 'The Night Listener': 4.0},'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,'The Night Listener': 4.5, 'Superman Returns': 4.0,'You, Me and Dupree': 2.5},'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,'You, Me and Dupree': 2.0},'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}
def sim_distance(prefs,person1,person2): # Get the list of shared_items
si={}
for item in prefs[person1]:
if item in prefs[person2]:
si[item]=1
# if they have no ratings in common, return 0
if len(si)==0:
return 0
# Add up the squares of all the differences
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
for item in prefs[person1] if item in prefs[person2]])
return 1/(1+sum_of_squares)
我刚开始使用 python,所以我很困惑这两个循环之间的区别:
一开始,
for item in prefs[person1]:
if item in prefs[person2]:
最后,
for item in prefs[person1] if item in prefs[person2]])
此外,他们在实现中使用了平方根,而在这段代码中,他们没有使用过。那么,这只是一个示例还是我们不在代码中使用? 此外,如果这两个 for 循环相同,当我像这样应用第二个 for 循环时,它们会给出不同的答案。
for item in prefs[person1]:
if item in prefs[person2]:
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)])
请您参考如下方法:
Also, they use the square root in implementation , which in this code, they have not used. So, is this just an example or we dont use in codes?
Please check this link The 'Unconfirmed' errata for this mistake by O'Reilly Media
最后一个方法应该是 return 1/(1+*sqrt(sum_of_squares)) 当然你可以在代码中使用它。 此外,示例中也存在错误。坐标错了。请引用链接
如评论中所述,第一个循环检查它们有多少个共同评分。
>>> recommendations.sim_distance(recommendations.critics,'Lisa Rose','Toby')
[FOR] Lisa : Lady in the Water
[FOR] Lisa : Snakes on a Plane
[IF] Toby : Snakes on a Plane
[FOR] Lisa : Just My Luck
[FOR] Lisa : Superman Returns
[IF] Toby : Superman Returns
[FOR] Lisa : You, Me and Dupree
[IF] Toby : You, Me and Dupree
[FOR] Lisa : The Night Listener
0.3483314773547883
第二个循环迭代项目值(评级)以进行减法。
根据上面的列表,这个循环必须进行 3 次迭代 (FOR == person1,IF == person2)。
